php實現快速排序

快速排序的思想是分冶法。php

取數組中間值=>遍歷數組剩餘元素=>小於中間值的放左邊,大於中間值的放右邊=>將左右循環如此直至不可再分->將已排好的合併
<?php

$arr = [11, 17, 29, 63, 45, 97, 12, 45, 34, 91, 64, 82, 76, 22, 77, 37, 85];

function quickSort($arr)
{
    if (count($arr) <= 1) return $arr;
    $index = (int)floor(count($arr) / 2);
    $value = $arr[$index];
    array_splice($arr, $index, 1);
    $left = $right = [];
    for ($i = 0; $i < count($arr); $i++) {
        if ($arr[$i] < $value) {
            array_push($left, $arr[$i]);
        } else {
            array_push($right, $arr[$i]);
        }
    }
    $left = quickSort($left);
    $right = quickSort($right);
    array_push($left, $value);
    return array_merge($left, $right);
}

echo join(", ", quickSort($arr));
相關文章
相關標籤/搜索