快速排序-挖坑法

<?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";

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值