欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

快速排序-php代码实现

程序员文章站 2022-07-09 21:28:25
= $r) return; $q = partition($a, $l, $r); quickSortInternally($a, $l, $q-1); quickSortInternally($a, $q+1, $r); } function partition(&$a, $l, $r): int... ......
<?php
function quicksort(array &$a)
{
    $n = count($a);
    quicksortinternally($a, 0, $n-1);
}
function quicksortinternally(array &$a, int $l, int $r)
{
    if ($l >= $r) return;
    $q = partition($a, $l, $r);
    quicksortinternally($a, $l, $q-1);
    quicksortinternally($a, $q+1, $r);
}
function partition(&$a, $l, $r): int
{
    $pivot = $a[$r];
    $i = $l;
    for ($j = $l; $j < $r; ++$j) {
        if ($a[$j] < $pivot) {
            $temp = $a[$i];
            $a[$i] = $a[$j];
            $a[$j] = $temp;
            ++$i;
        }
    }
    $temp = $a[$i];
    $a[$i] = $a[$r];
    $a[$r] = $temp;
    return $i;
}
$a1 = [1,4,6,2,3,5,4];
$a2 = [2, 2, 2, 2];
$a3 = [4, 3, 2, 1];
$a4 = [5, -1, 9, 3, 7, 8, 3, -2, 9];
quicksort($a1);
print_r($a1);
quicksort($a2);
print_r($a2);
quicksort($a3);
print_r($a3);
quicksort($a4);
print_r($a4);