发布于 5年前
php 快速排序
代码:
$arr=[3,5,2,7,4,1,1,10];
var_export(quick_sort($arr));
function quick_sort($data){
if(count($data)<=1){
return $data;
}
$pivot=$data[0];
unset($data[0]);
$A1=[];
$A2=[];
foreach ($data as $val){
if($val<$pivot){
$A1[]=$val;
}else{
$A2[]=$val;
}
}
$A1= quick_sort($A1);
$A2= quick_sort($A2);
return array_merge($A1,[$pivot],$A2);
}
输出:
array (
0 => 1,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5,
6 => 7,
7 => 10,
)