一个没有循环的排序方法

2019-07-29  本文已影响0人  猿来是八阿哥

不使用循环,对数组进行排序

代码

<?php
// 不使用循环对 $data 进行排序
function random_array($length=10){
    $walk = array_fill(0, $length, 0);
    array_walk($walk, function($value, $key) use (&$data){
        $data[$key] = random_int(0, 100);
    });
    return $data;
}
$data = random_array(10);

define('RECURSION_SORT_MAX',  99999999);
define('RECURSION_SORT_MIN', -99999999);
function find_max_with_bound($data, $bound=RECURSION_SORT_MAX, $max=RECURSION_SORT_MIN, $index=0, $max_index=-1){
    if($index != count($data)) {
        if ($bound >= $data[$index] && $data[$index] >= $max) {
            $max = $data[$index];
            $max_index = $index;
        }
        list($max_index, $max) = find_max_with_bound($data, $bound, $max, $index+1, $max_index);
    }
    return [$max_index, $max];
}
function recursion_sort($data, &$sorted=[]){
    if(count($data) != count($sorted)){
        $sorted_max = count($sorted) == 0 ? RECURSION_SORT_MAX : $sorted[count($sorted)-1];
        list($max_index, $max) = find_max_with_bound($data, $sorted_max);
        $data[$max_index] = RECURSION_SORT_MIN;
        array_push($sorted, $max);
        recursion_sort($data, $sorted);
    }
    return $sorted;
}
echo 'data before sorting: '.PHP_EOL;
print_r($data);
echo 'data sorted: '.PHP_EOL;
print_r(recursion_sort($data));

结果

data before sorting: 
Array
(
    [0] => 45
    [1] => 96
    [2] => 30
    [3] => 83
    [4] => 80
    [5] => 36
    [6] => 65
    [7] => 72
    [8] => 14
    [9] => 46
)
data sorted: 
Array
(
    [0] => 96
    [1] => 83
    [2] => 80
    [3] => 72
    [4] => 65
    [5] => 46
    [6] => 45
    [7] => 36
    [8] => 30
    [9] => 14
)
上一篇 下一篇

猜你喜欢

热点阅读