views:

76

answers:

2

usort and uasort use a comparison function which is slow because it must be computed every time a comparison is needed between to elements of an array. Other languages, like Python, let you sort an array using a key function which gets evaluated only once per element in the array. What's the best way to do this in PHP?

A: 
function sort_with_keyfunc($array, $keyfunc) {
    $keys = array_map($keyfunc, $array); // get the keys for each item
    array_multisort($keys, $array); // sort $array according to the sorted keys
    return $array;
}

This also maintains key=>value pairs in associative arrays.

troutinator
Uh whaaaaat? You're answering your own questions immediately - in less than two minutes??
Rudu
Its a nice quick way to get those badges :)
Anti Veeranna
This guy is also [blogging about this question on his site](http://www.nathanieltroutman.net/content/sorting-arrays-php-using-key-function). It has many more details and benchmark results.
shamittomar
+2  A: 

You need faster? Use Quicksort:

<?php
function quicksort( $arr, $l = 0 , $r = NULL ) {
// when the call is recursive we need to change
// the array passed to the function earlier
    static $list = array();
    if( $r == NULL )
        $list = $arr;

    if( $r == NULL )
        $r = count($list)-1;//last element of the array

    $i = $l;
    $j = $r;

    $tmp = $list[(int)( ($l+$r)/2 )];

    // partion the array in two parts.
    // left from $tmp are with smaller values,
    // right from $tmp are with bigger ones
    do {
        while( $list[$i] < $tmp )
            $i++;

        while( $tmp < $list[$j] )
            $j--;

        // swap elements from the two sides
        if( $i <= $j ) {
            $w = $list[$i];
            $list[$i] = $list[$j];
            $list[$j] = $w;

            $i++;
            $j--;
        }
    }while( $i <= $j );

    // devide left side if it is longer the 1 element
    if( $l < $j )
        quicksort(NULL, $l, $j);

    // the same with the right side
    if( $i < $r )
        quicksort(NULL, $i, $r);

    // when all partitions have one element
    // the array is sorted

    return $list;
}
?>
shamittomar
ee gads man, using short tags like that!!! EEEK!! (side note, I now feel violated)
Brad F Jacobs
-1 [PHP’s `sort` function](http://php.net/sort) is already using Quicksort: “Like most PHP sorting functions, `sort()` uses an implementation of Quicksort.”
Gumbo
@Gumbo: Nice point. I never noticed that. :)
shamittomar
@premiso: Didn't think it was such an issue. Changed the short tags to full tags. :)
shamittomar
@shamittomar I was just yankin your chain!
Brad F Jacobs