常规方法,快速排序
<?php
function quick_sort(array $arr) : array
{
if (!is_array($arr)) return [];
$length = count($arr);
if ($length <= 1) return $arr;
$left = $right = [];
for ($i = 1; $i < $length; $i++) {
if ($arr[$i] < $arr[0]) {
$left[] = $arr[$i];
} else {
$right[] = $arr[$i];
}
}
$left = quick_sort($left);
$right = quick_sort($right);
return array_merge($left, [$arr[0]], $right);
}
$arr = [22, 7, 1, 34, 435, 8, 523, 3, 21, 2, 24, 654, 55, 32, 12];
$res = quick_sort($arr);
echo join('-', $res);
“挖坑法” 快速排序
<?php
function quick_sort(array $arr) : array
{
switch (count($arr)) {
case 0 :
return [];
case 1 :
return $arr;
case 2 :
return ($arr[0] < $arr[1]) ? [$arr[0], $arr[1]] : [$arr[1], $arr[0]];
}
$pivot = $arr[0];
$leftHead = 0;
$rightHead = count($arr) - 1;
$index = 0;
$compare = 'right';
while (true) {
if ($leftHead == $rightHead) {
$left = array_slice($arr, 0, $leftHead);
$right = array_slice($arr, ($leftHead + 1));
$mid = [$pivot];
return array_merge(quick_sort($left), $mid, quick_sort($right));
}
if ('right' == $compare) {
if ($arr[$rightHead] < $pivot) {
$arr[$index] = $arr[$rightHead];
$leftHead++;
$index = $rightHead;
$compare = 'left';
} else {
$rightHead--;
}
} else {
if ($arr[$leftHead] > $pivot) {
$arr[$index] = $arr[$leftHead];
$index = $leftHead;
$rightHead--;
$compare = 'right';
} else {
$leftHead++;
}
}
}
}
$arr = [22, 7, 1, 34, 435, 8, 523, 3, 21, 2, 24, 654, 55, 32, 12];
$res = quick_sort($arr);
echo join('-', $res);