Complex13 has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to wrap my head around how the sort function does it's deed.There are several examples as to different uses for sort, but I would like to know how the operation takes place.
@numbers = (7, 12, 49, 44); @sorted = sort { $a <=> $b } @numbers;
I understand the return codes of 1, 0, and -1 but what happens after the first comparison? I'm assuming element 0 is the first instance of $a and element 1 is $b. Those two are compared. The return value would be -1 since 7 is less than 12. So now what happens? We have established that element 0 is less than element 1. Is element 0 now compared to the rest of the elements with each subsequent element taking over the value of $b for comparison? If something is smaller than element 0, is that value now used for $a until all elements to compare have been exhausted? Once the first compare has been exhausted to find the smallest number that value is now assigned to the new array as element zero, sort of like a king of the hill for the smallest number?
Sorry for the odd post but I've seen several examples of what happens in the end but not what is happening along the way for the sort command.
Mike W
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: how sort works
by ikegami (Patriarch) on Mar 07, 2011 at 04:49 UTC | |
|
Re: how sort works
by roboticus (Chancellor) on Mar 07, 2011 at 05:01 UTC | |
|
Re: how sort works
by sauoq (Abbot) on Mar 07, 2011 at 03:04 UTC | |
by JavaFan (Canon) on Mar 07, 2011 at 17:18 UTC | |
by tilly (Archbishop) on Mar 08, 2011 at 07:35 UTC | |
by JavaFan (Canon) on Mar 08, 2011 at 10:19 UTC | |
|
Re: how sort works
by Khen1950fx (Canon) on Mar 07, 2011 at 11:40 UTC | |
by Anonymous Monk on Mar 07, 2011 at 12:15 UTC | |
|
Re: how sort works
by locked_user sundialsvc4 (Abbot) on Mar 09, 2011 at 14:52 UTC |