<?php
function buildHeap(&$arr)
{
$length = count($arr);
for ($i = intval($length / 2) - 1; $i >= 0; $i--) {
toHeap($i, $length - 1, $arr);
}
}
function toHeap($i, $n, &$arr)
{
$max = $i;
$left = 2 * $i + 1;
$right = 2 * $i + 2;
if ($left <= $n && $arr[$max] < $arr[$left]) {
$max = $left;
}
if ($right <= $n && $arr[$max] < $arr[$right]) {
$max = $right;
}
if ($max != $i) {
list($arr[$max], $arr[$i]) = [$arr[$i], $arr[$max]];
toHeap($max, $n, $arr);
}
}
function heapSort(&$arr)
{
$length = count($arr);
buildHeap($arr);
while ($length > 1) {
list($arr[0], $arr[$length - 1]) = [$arr[$length - 1], $arr[0]];
$length--;
toHeap(0, $length - 1, $arr);
}
}
$arr = [49, 38, 65, 97, 76, 13, 27, 50, 101, 1];
heapSort($arr);
var_dump($arr);
php 堆排序
最新推荐文章于 2021-05-14 22:28:47 发布