开发者

Best way to sort an array in PHP using a key-function?

usort and uasort use a comparison function which is slow because it must be computed every time a comparison is needed bet开发者_StackOverflow社区ween 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?


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;
}
?>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜