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
2010-09-16 19:51:02
Uh whaaaaat? You're answering your own questions immediately - in less than two minutes??
Rudu
2010-09-16 19:53:12
Its a nice quick way to get those badges :)
Anti Veeranna
2010-09-16 19:55:50
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
2010-09-16 20:05:50
+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
2010-09-16 19:54:08
ee gads man, using short tags like that!!! EEEK!! (side note, I now feel violated)
Brad F Jacobs
2010-09-16 19:56:19
-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
2010-09-16 20:00:29
@premiso: Didn't think it was such an issue. Changed the short tags to full tags. :)
shamittomar
2010-09-16 20:34:50