Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Answer: How do I write my own sorting routine?

by jarich (Curate)
on Dec 22, 2003 at 05:57 UTC ( #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
[choroba]: suddenly, a weird noise can be heard, and the conductor stops them
[choroba]: (sorry, was interrupted by a call)
[choroba]: What was that? asks he
[choroba]: and the triangle player says, "That was me. It's written here in the score"
[choroba]: and shows a bar with a note "ohne Triangel"
[choroba]: where "ohne" means "will bend" in Czech
[LanX]: one-day-the- triangle-player-of -an-orchestra-gets -very-sick xD
[choroba]: :)

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2017-03-27 12:00 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (319 votes). Check out past polls.