Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Re: Re: reversing a sort...

by nardo (Friar)
on May 09, 2001 at 02:49 UTC ( [id://78981]=note: print w/replies, xml ) Need Help??


in reply to Re: Re: reversing a sort...
in thread reversing a sort...

reverse sort { arbitrary code } @list will always be less efficient than sort { arbitrary code with $a and $b swapped } @list

Not always, the number of comparisons and swaps performed by sort will depend on the order of the list. On my machine, reverse sort {$a <=> $b} (1..100000); is faster than sort {$b <=> $a} (1..100000);

For almost all cases, you are correct, but it is not _always_ the case.

Replies are listed 'Best First'.
Re: Re: Re: Re: reversing a sort...
by chipmunk (Parson) on May 09, 2001 at 05:09 UTC
    I quite intentionally did not say one would be always be "faster". I said reverse sort is less efficient. sort and reverse sort are both O(n log n), but the one with reverse has a larger constant factor and is less efficient.

    By the way, if you want to know the fastest way to sort the list (1..100_000) in descending order, it's: reverse (1 .. 100_000); ;)

    Update: Doh. As Tilly explains below, I totally messed up the Big O analysis. Anyway, there is an added inefficiency with reverse sort, that's my point. :)

      Actually the one with the reverse has the exact same constant factor as the regular sort.

      The additional inefficiency is O(n), not O(n log n). Plus it is O(n) with a fairly small factor...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://78981]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2024-04-19 20:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found