Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Check if sort has changed order

by davido (Cardinal)
on May 10, 2013 at 15:07 UTC ( [id://1032970]=note: print w/replies, xml ) Need Help??


in reply to Check if sort has changed order

Sorting is an O(n log n) operation. Testing a list for sortedness is an O(n) operation. Test first, then sort if necessary.

use strict; use warnings; use List::Util qw( first ); my @x = qw( 1 3 2 4 5 ); if( defined first { $x[$_] > $x[$_+1] } 0 .. $#x - 1 ) { @x = sort { $a <=> $b } @x; }

Strategies for testing whether a change has been made after sorting has been applied will either involve a checksum of some type (ie, take an MD5 of the list's contents before and again after), or keeping a copy of the pre-sorted list for comparison. One way you're throwing CPU cycles at the problem, and the other way, you're throwing memory at it. If you can just check whether sorting is necessary ahead of time, you conserve both.


Dave

Replies are listed 'Best First'.
Re^2: Check if sort has changed order
by Anonymous Monk on May 10, 2013 at 23:17 UTC

    If you can just check whether sorting is necessary ahead of time, you conserve both.

    I think I agree with you :)

    I thought maybe its detectible from within sort callback if order has changed, but it doesn't look that way

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-25 09:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found