算法系列-堆排序
定义
堆排序指利用堆这种数据结构所设计的一种排序算法
- 大顶堆:每个节点的值都大于或等于其子节点的值,在堆排序算法中用于升序排列;
- 小顶堆:每个节点的值都小于或等于其子节点的值,在堆排序算法中用于降序排列;
原理
- 创建一个堆H[0,1,…,n-1,n]
- 把堆首(最大值)和堆尾互换
- 把堆的尺寸缩小1,并调用shif_down(0),目的时把新的数组顶端数据调整到相应位置
- 重复步骤2,直到堆的尺寸为1
PHP实现
function buildMaxHeap(&$arr)
{
global $len;
for ($i = floor($len/2); $i >= 0; $i--) {
heapify($arr, $i);
}
}
function heapify(&$arr, $i)
{
global $len;
$left = 2 * $i + 1;
$right = 2 * $i + 2;
$largest = $i;
if ($left < $len && $arr[$left] > $arr[$largest]) {
$largest = $left;
}
if ($right < $len && $arr[$right] > $arr[$largest]) {
$largest = $right;
}
if ($largest != $i) {
swap($arr, $i, $largest);
heapify($arr, $largest);
}
}
function swap(&$arr, $i, $j)
{
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
function heap_sort($arr) {
global $len;
$len = count($arr);
buildMaxHeap($arr);
for ($i = count($arr) - 1; $i > 0; $i--) {
swap($arr, 0, $i);
$len--;
heapify($arr, 0);
}
return $arr;
}
//例子
$numbers = [1,3,4,22,88,33,31,42];
print_r(heap_sort($numbers));
16 条评论
sinequan no rx · 2021年1月10日 下午1:34
I precisely desired to say thanks again. I’m not certain the things I could possibly have accomplished in the absence of the aspects contributed by you about my area. Completely was a challenging case for me, but being able to view a expert approach you dealt with it forced me to cry for contentment. Extremely grateful for the advice and believe you are aware of a powerful job that you’re accomplishing educating many others all through a blog. I’m certain you’ve never come across all of us.