Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Answer: How do I write my own sorting routine?

( #316312=categorized answer: print w/ replies, xml ) Need Help??

Q&A > sorting > How do I write my own sorting routine? contributed by jarich

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

Comment on Answer: How do I write my own sorting routine?
Select or Download Code
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
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (11)
As of 2014-08-20 15:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (116 votes), past polls