in reply to argmin & argmax

I've always wished that Sort::Key provided such functions.

In case you're not familiar with Sort::Key, at its core is keysort KEY_GENERATOR LIST, which could be used as follows:

# Sort the objects according to the value of their `name` attribute. my @sorted_objects = keysort { $_->name } @unsorted_objects;

It has variants.

# Sort the objects according to the value of their uint id my @sorted_objects = ukeysort { $_->id } @unsorted_objects;

You'd think the module would also provide similar subs to find the elements that would sort first and/or last, but it doesn't.

Your argmin and argmax sub are effectively specific variants of those missing subs.

Replies are listed 'Best First'.
Re^2: argmin & argmax
by sleet (Monk) on May 13, 2025 at 02:13 UTC

      Nice ...or is it? Seeing as it returns the top x values, is the algorithm used O(n) as desired, or O(n log n) like a sort? That said, the extra log n doesn't add much, though.