代码:
<?php
function heap_sort($arr = []){
adjust_heap($arr); // 初始化调整堆
$tmp_arr = [];
while(!empty($arr)){
$tmp_arr[] = array_shift($arr);
adjust_heap($arr);
}
return $tmp_arr;
}
function adjust_heap(&$arr = []){
$arr_len = count($arr);
$parent_index = intval($arr_len/2)-1;
while ($parent_index > -1) {
$left_child_index = (2 * $parent_index) + 1; // 至少存在左子树
$right_child_index = (2 * $parent_index) + 2;
$winner_index = $left_child_index;
// 注意比较运算法 <
if(!empty($arr[$right_child_index]) && ($arr[$right_child_index] < $arr[$left_child_index])){
$winner_index = $right_child_index;
}
if ($arr[$parent_index] > $arr[$winner_index]) {
$tmp = $arr[$parent_index];
$arr[$parent_index] = $arr[$winner_index];
$arr[$winner_index] = $tmp;
}
$parent_index--;
}
}
// $arr = [3, 2, 8];
// $arr = [2, 13, 1, 5, 99, 234, 23, 33];
$arr = [3, 34, 443, 123, 2, 1, 543, 534234, 19, 234,9434];
$arr = heap_sort($arr);
print_r($arr);
输出:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 19
[4] => 34
[5] => 123
[6] => 234
[7] => 443
[8] => 543
[9] => 9434
[10] => 534234
)