<?php
/*function quick_sort(&$arr, $start, $end)
{
if ($start < $end) {
$pivot_index = partition($arr, $start, $end);
quick_sort($arr, $start, $pivot_index - 1);
quick_sort($arr, $pivot_index + 1, $end);
}
}*/
function quick_sort(&$arr, $start, $end)
{
$border_stack = [];
$border_stack[] = ['start' => $start, 'end' => $end];
while (!empty($border_stack)) {
$border = array_pop($border_stack); // 出栈
$pivot_index = partition($arr, $border['start'], $border['end']);
if ($pivot_index - 1 > $border['start']) {
$border_stack[] = ['start' => $border['start'], 'end' => $pivot_index - 1]; // 入栈
}
if ($pivot_index + 1 < $border['end']) {
$border_stack[] = ['start' => $pivot_index + 1, 'end' => $border['end']]; // 入栈
}
}
}
/*function partition(&$arr, $start, $end)
{
$left_index = $start;
$right_index = $end;
$pivot = $arr[$start];
while ($left_index < $right_index) {
while ($left_index < $right_index && $arr[$right_index] >= $pivot) {
$right_index--;
}
while ($left_index < $right_index && $arr[$left_index] <= $pivot) {
$left_index++;
}
if ($left_index < $right_index) {
$temp = $arr[$left_index];
$arr[$left_index] = $arr[$right_index];
$arr[$right_index] = $temp;
}
}
// 左右指针重叠停止循环比较,交换元素
$pivot_index = $left_index;
$arr[$start] = $arr[$pivot_index];
$arr[$pivot_index] = $pivot;
return $pivot_index;
}*/
function partition(&$arr, $start, $end)
{
$left_index = $start;
$right_index = $end;
$index = $start;
$pivot = $arr[$start];
while ($left_index <= $right_index) {
while ($left_index <= $right_index) {
if ($arr[$right_index] < $pivot) {
$arr[$index] = $arr[$right_index];
$index = $right_index;
$left_index++;
break;
}
$right_index--;
}
while ($left_index <= $right_index) {
if ($arr[$left_index] > $pivot) {
$arr[$index] = $arr[$left_index];
$index = $left_index;
$right_index--;
break;
}
$left_index++;
}
}
$arr[$index] = $pivot;
return $index;
}
$arr = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48, 3, 50, 0, 0, -1, -3, 51, -2, -1, -8];
/*$arr = [];
for ($i = 0; $i < 20; $i++) {
$arr[$i] = mt_rand(0, 100);
}*/
echo join(',', $arr);
echo "\n";
$startTime = microtime(1);
quick_sort($arr, 0, count($arr) - 1);
echo join(',', $arr);
echo "\n";
echo "use time: ", microtime(1) - $startTime, "s\n";
stack_quick_sort
最新推荐文章于 2024-06-03 15:42:36 发布