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

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? - Answer 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;
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?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (11)
As of 2016-08-24 08:39 GMT
Find Nodes?
    Voting Booth?
    The best thing I ever won in a lottery was:

    Results (340 votes). Check out past polls.