What is the easiest way to get a key with the highest value from a hash in Perl?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
While the solution with sort:
found in some of the other answers is quite elegant, it doesn’t perform as nicely as it looks. First off, the sort transforms an
O(n)search search operation into anO(n log n)one. Secondly, the sort solution hasn log nhash look-ups. Hash look-ups are very good for certain operations, but when working with the entire hash, look-ups will be slower than usingeach,keys, orvaluesto iterate through the data structure. This is because the iterators do not need to calculate the hashes of keys, nor do they need to repeatedly walk through bins to find the values. And the overhead is not constant, but increasing as the hashes get larger.Here are a few faster solutions:
Here is a solution using the
eachiterator (anO(1)operation donentimes):Or a faster version that trades memory for speed (it makes a copy of the hash):
Here is the performance with various hash sizes:
As you can see, if memory isn’t much of an issue, the version with internal arrays is fastest, closely followed by the
eachiterator, and in a distant third…sort