Sorting data the way YOU want it sorted
Archive - Originally posted on "The Horse's Mouth" - 2011-08-05 08:00:52 - Graham EllisPieces of program code ... subroutines, functions, macros, procedures, user commands, methods ... are stored with a name, and within many programming languages are actually stored in the same memory area and under the same structure as other named values - variables. This means that you can pass in a piece of code to another function as a parameter. But why would you want to do that?
Let's take an example.
I've written a generic sorting routine that takes an array (I'm using PHP terms and examples today as I'm running a PHP course this week) as its parameter, and sorts it "in situ". But I want my sort routine to be flexible in how it decided which records come in before (and which come after) each other; the clever bit of sorting is to work out which comparisons to make, and to manage those comparisons to keep them down to a reasonable level. So I'm going to write a seperate function that my generic code can call to make the comparison that I want, and I'm going to pass the name of that function into the generic sorting code.
There's an example I wrote yesterday to illustrate that - source code [here] and run it [here] on our server.
a) The main code calls the sorter routine:
mysorter($things,"raise");
b) The mysorter function collects that name of the comparator as follows:
function mysorter(&$arr,$codename) {
and then calls the comparator usingthe variable namein which the comparator function is defined:
$wanttoswap = $codename($arr[$j+1],$arr[$j]);
c) The comparator function actually does the comparison of two items.
The comparator function MUST take the number of parameters, in the order required, that's defined within the sorter function, and it must return a result in the form that that the sorter function expects.
In a practical application, I would NOT write "mysorter". I would use a standard PHP function - but I would still pass in the name of one of my own pieces of code if I wanted a somewhat unusual sort order; my example sorts numbers based on the remainder when the numbers are divided by 10, and that's a good example of the sort of place I would use a mechanism such as this, which is known as a callback. PHP's standard functions which sort using callbacks are usort, uasort and uksort. In each case, you pass them the array to be sorted, and the name of your own function which takes two parameters and returns a -1 / 0 / +1 value to indicate that the first parameter is to be considered to be less than, equal to, or greater than the second one for sorting purposes.
Other examples / articles - in Python, in Lua, and in Perl.