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

Re: sort a hash array

by wog (Curate)
on Nov 18, 2001 at 07:57 UTC ( [id://126082]=note: print w/replies, xml ) Need Help??


in reply to sort a hash array

my @array1 = sort { $queryterms{$b} <=> $queryterm{$a} || $a cmp $b } keys %queryterms; my @array2 = map { $queryterms{$_} } @array1;

Smaller. Faster. Alternately one could just do my @sortedkeys = sort { $queryterms{$b} <=> $queryterm{$a} || $a cmp $b } keys %queryterms; and then use @queryterm{@sortkeys} instead of @array1 and @sortedkeys (better named, IMO) instead of @array1.

update: added key comparing to sort, like the original had.

(update: I would note that if you can't use perl's built-in sort, you probably should use a better algorithm. Yours takes O(N**2) comparisions where as perl's sort algorithm (and most of the good sorting algortihms) average O(N log N) comparisions. )

(I forewarn that I have not tested the code here.)

Replies are listed 'Best First'.
Re: Re: sort a hash array
by fuzzysteve (Beadle) on Nov 18, 2001 at 09:45 UTC
    I bow to your superiour knowledge.
    In my own defence (or probably damnation) Most of the code is a quick hack I threw together to solve a problem at hand. It worked, so I didn't tweak it. Looking back, I should have.
    As an aside, I didn't pick the sort routine as for its speed, I picked it for its ease of coding. this is lifted from some code thats going to be run nightly, at a time when the servers going to be unused. in a test on sample data, it doesn't take too long to work, so is suitable for the job.
    In the end, I'm not arguing with you. Its not pretty, its not fast. It's also not a good use of the functions perl has available. but it does work, and its simple to understand.
    Thanks for the code btw, as its here, I should probably try it

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-03-28 10:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found