Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: How do I write my own sorting routine?

by jarich (Curate)
on Dec 22, 2003 at 05:57 UTC ( [id://316312]=note: print w/replies, xml ) Need Help??


in reply to How do I write my own sorting routine?

If you have a hash which specifies an ordering for values, then your sorting is much easier:
my %hash = ( "very slow" => 1, "slow" => 2, "slowish" => 3, "medium" => 4, "acceptable" => 5, "fast" => 6, "very fast" => 7, );
Now to sort, we just compare the array elements as keys into the hash:
my @sorted = sort { $hash{$a} <=> $hash{$b} } @array;
Hence:
my @array = ("slow", "very fast", "fast", "very slow", "acceptable");
would sort into:
very slow, slow, acceptable, fast, very fast

Replies are listed 'Best First'.
Re: Answer: How do I write my own sorting routine?
by Roger (Parson) on Dec 22, 2003 at 12:44 UTC
    I believe the correct sorting should be
    my @sorted = sort { $hash{$a} <=> $hash{$b} } @array;
    Note the use of the 'spaceship' comparison operator instead of the cmp operator. The reason is that cmp compares the values based on string values, while <=> compares the values based on numerical values. So if your hash has values 1 to 10, the ordering with cmp produces 1,10,2,3,..., while ordering with <=> produces 1,2,3....,10.

Log In?
Username:
Password:

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

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

    No recent polls found