<?php
// 快速排序-挖坑法
function quickSort(&$arr, $startIndex, $endIndex)
{
// 递归结束条件:$startIndex大于等于$endIndex的时候
if ($startIndex >= $endIndex) {
return;
}
// 得到基准元素位置
$pivotIndex = partition($arr, $startIndex, $endIndex);
// 用分治法递归数列的两部分
quickSort($arr, $startIndex, $pivotIndex - 1);
quickSort($arr, $pivotIndex + 1, $endIndex);
}
function partition(&$arr, $startIndex, $endIndex)
{
// 取第一个位置的元素作为基准元素
$pivot = $arr[$startIndex];
$left = $startIndex;
$right = $endIndex;
// 坑的位置,初始等于$pivot的位置
$index = $startIndex;
// 大循环在左右指针重合或者交错时结束
while ($right >= $left) {
// $right指针从右向左进行比较
while ($right >= $left) {
// 比$pivot小
if ($arr[$right] < $pivot) {
// $arr[$left] = $arr[$right];
$arr[$index] = $arr[$right]; // 把$right所指向的元素填入坑中
$index = $right; // $right位置成为新坑的位置
$left++; // 左指针向右移一位
break;
}
$right--; // 大于等于$pivot,右指针向左移一位
}
// $left指针从左向右进行比较
while ($right >= $left) {
// 比$pivot大
if ($arr[$left] > $pivot) {
// $arr[$right] = $arr[$left];
$arr[$index] = $arr[$left]; // 把$left所指向的元素填入坑中
$index = $left; // $left位置成为新坑的位置
$right--; // 右指针向左移一位
break;
}
$left++; // 小于等于$pivot,左指针向右移一位
}
}
$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 < 100; $i++) {
$arr[$i] = mt_rand(0, 100);
}*/
$startTime = microtime(1);
quickSort($arr, 0, count($arr) - 1);
echo join(',', $arr);
echo "\n";
echo "use time: ", microtime(1) - $startTime, "s\n";
快速排序-挖坑法
最新推荐文章于 2024-02-27 17:01:36 发布