导航

快速排序

Posted on 2020-11-16 15:24  玻璃星  阅读(30)  评论(0编辑  收藏  举报
<?php
function quick_sort($arr)
{
    $count = count($arr);
    if ($count <= 1) {
        return $arr;
    }
    $left = [];
    $right = [];

    for($i=1;$i<$count;$i++){
        if($arr[$i]<$arr[0]){
            array_push($left,$arr[$i]);
        }else{
            array_push($right,$arr[$i]);
        }
    }

    $left = quick_sort($left);
    $right = quick_sort($right);

    array_push($left,$arr[0]);
    $result = array_merge($left,$right);
    return $result;
}

$arr = array(4,3,2,1,9,8,7,6,5);
echo "<pre>";
print_r(quick_sort($arr));

/**
 * Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
)
 */