首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 實現堆積排序 (HeapSort) 與效能基準測試

     編輯:PHP 綜合知識

純 PHP 實現 HeapSort 演算法,並與簡單選擇排序、內建 sort() 進行效能對比。

HeapSort 類別

class HeapSort {
    var $a;
    function setArray($a) { $this->a = $a; }
    function runValue($b, $c) { /* 向下調整堆,b=起始索引, c=結束索引 */ }
    function getArray() {
        $n = count($this->a);
        // 建堆
        for ($i=floor(($n-1)/2); $i>=1; $i--) $this->runValue($i, $n-1);
        // 排序
        for ($i=1; $i<$n; $i++) {
            $end = $n-$i;
            $this->runValue(1, $end);
            // 交換堆頂與末尾
            $t=$this->a[1]; $this->a[1]=$this->a[$end]; $this->a[$end]=$t;
        }
        return $this->a;
    }
}

對比類別:簡單選擇排序

class SimpleSort {
    var $a;
    function setArray($a) { $this->a=$a; }
    function getArray() {
        for ($i=1; $ia)-1; $i++) {
            $max=$this->a[$i]; $id=$i;
            for ($j=$i+1; $ja); $j++)
                if ($this->a[$j]>$max) { $max=$this->a[$j]; $id=$j; }
            if ($id!=$i) { $t=$this->a[$id]; $this->a[$id]=$this->a[$i]; $this->a[$i]=$t; }
        }
        return $this->a;
    }
}

效能測試結果 (10,000 元素隨機陣列)

演算法耗時 (秒)備註
HeapSort~0.15O(n log n),PHP 解釋執行仍有優勢
SimpleSort (選擇排序)~12.5O(n²),極慢
內建 sort()~0.002C 核心實現,快 2-3 個數量級

結論

  • PHP 實現複雜演算法僅適合教學或極小數據量。
  • 生產環境**務必使用內建 sort()/usort()**等核心函數。
  • HeapSort 代碼展示了「建堆 → 逐次取堆頂 → 調整」的經典流程。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved