in reply to Sorting through a rollover

I learned this from ysth other day:

use strict; use warnings; my @num = qw( 00002 00003 00001 99999 99998 ); @num = sort { ( $a < 50000 ) <=> ( $b < 50000 ) || $a <=> $b } @num; print "sorted: @num \n"; # sorted: 99998 99999 00001 00002 00003

Replies are listed 'Best First'.
Re^2: Sorting through a rollover
by RazorbladeBidet (Friar) on Feb 10, 2005 at 17:56 UTC
    if

    my @num = qw( 49998 49999 50000 50001 50002 500003)

    you get

    sorted: 50000 50001 50002 500003 49998 49999

    There's got to be a link between the number shown on the page.

    Update

    How about

    sort { abs( $a - $b ) > 200 ? $b <=> $a : $a <=> $b }


    Y'know I just thought of something - looks like you're reading from a log of some sort

    why would you have to sort at all?

    Is it even necessary? (Just checking)
      Or slightly more compactly (using trinary math instead of the trinary operator):
      (abs($a - $b) <=> $max_spread) * ($b <=> $a)
      where $max_spread is the maximum range you expect your numbers to cover before wrapping. 50_000 might be a better choice than 200.

      Caution: Contents may have been coded under pressure.
        The 200 was based upon the fact that he's showing 200 messages.

        either way, I think as long as it's less than the possible number of id's, it'll be ok

        (or maybe less than half?)