<?php
// 快速排序-指针交换法
function quickSort(&$arr, $startIndex, $endIndex)
{
// 递归结束条件:$startIndex大于等于$endIndex的时候
if ($startIndex >= $endIndex) {
return;
}
// 得到基准元素位置
$pivotIndex = partition($arr, $startIndex, $endIndex);
// echo $pivotIndex . "\n";
// print_r($arr);
// exit;
// 用分治法递归数列的两部分
quickSort($arr, $startIndex, $pivotIndex - 1);
quickSort($arr, $pivotIndex + 1, $endIndex);
}
// 分治法找出基准元素索引位置
function partition(&$arr, $startIndex, $endIndex)
{
static $count = 0;
$count++;
// 取第一个位置的元素作为基准元素
$pivot = $arr[$startIndex];
$left = $startIndex;
$right = $endIndex;
// 大循环在左右指针重合时结束
while ($left != $right) {
//控制right指针比较并左移
// 从right指针开始,把指针所指向的元素和基准元素做比较。如果大于等于pivot,则指针向左移动;如果小于pivot,则right指针停止移动,切换到left指针
while
// ($left < $right && $arr[$right] > $pivot) {
($left < $right && $arr[$right] >= $pivot) {
$right--;
}
//控制left指针比较并右移
// left指针所指向的元素和基准元素做比较。如果小于等于pivot,则指针向右移动;如果大于pivot,则left指针停止移动
while
($left < $right && $arr[$left] <= $pivot) {
$left++;
}
//交换left和right指向的元素
// right指针和left指针都停下的时候,我们让left和right指向的元素进行交换
if ($left < $right) {
$temp = $arr[$left];
$arr[$left] = $arr[$right];
$arr[$right] = $temp;
}
}
// 当left和right指针重合之时,我们让pivot元素和left与right重合点的元素进行交换
// echo '$left:' . $left . ',$right:' . $right . ',$count:' . $count . "\n";
$temp = $arr[$left];
$arr[$left] = $arr[$startIndex];
// $arr[$left] = $pivot;
$arr[$startIndex] = $temp;
// echo join(',', $arr) . "\n";
return $left;
}
$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 = [1, 2, 3, 4, 5, 6, 7, 8];
$arr = [4, 7, 6, 5, 3, 2, 8, 1, 4];
/*$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";
快速排序-指针交换法
最新推荐文章于 2023-07-12 10:59:32 发布