PHP快速排序算法


說明:

  通過設置一個初始中間值,來將需要排序的數組分成3部分,小於中間值的左邊,中間值,大於中間值的右邊,繼續遞歸用相同的方式來排序左邊和右邊,最后合並數組

 

示例:

<?php

$a = array(2,13,42,34,56,23,67,365,87665,54,68,3);

function quick_sort($a)
{
    // 判斷是否需要運行,因下面已拿出一個中間值,這里<=1
    if (count($a) <= 1) {
        return $a;
    }

    $middle = $a[0]; // 中間值

    $left = array(); // 接收小於中間值
    $right = array();// 接收大於中間值

    // 循環比較
    for ($i=1; $i < count($a); $i++) { 

        if ($middle < $a[$i]) {

            // 大於中間值
            $right[] = $a[$i];
        } else {

            // 小於中間值
            $left[] = $a[$i];
        }
    }

    // 遞歸排序划分好的2邊
    $left = quick_sort($left);
    $right = quick_sort($right);

    // 合並排序后的數據,別忘了合並中間值
    return array_merge($left, array($middle), $right);
}

print_r(quick_sort($a));

 

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM