純 PHP 實現 HeapSort 演算法,並與簡單選擇排序、內建 sort() 進行效能對比。
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;
}
}
| 演算法 | 耗時 (秒) | 備註 |
|---|---|---|
| HeapSort | ~0.15 | O(n log n),PHP 解釋執行仍有優勢 |
| SimpleSort (選擇排序) | ~12.5 | O(n²),極慢 |
| 內建 sort() | ~0.002 | C 核心實現,快 2-3 個數量級 |
sort()/usort()**等核心函數。