自底向上:
//增加/减少 已有节点值
Heap_Increase_Key
//向堆插入新的节点
HeapInsert
自顶向下:
//替换堆顶后,维持堆函数
KeepHeap
//弹出堆顶函数
Pop
#include <iostream>
using namespace std;
//增加已有节点值
void Heap_Increase_Key(int * array,int& len,int h,int increase_value)
{
if (array == NULL || h >= len||increase_value<0)
return;
array[h] = increase_value;
int parent = (h -1)/ 2;
while (parent >= 0 && array[h] > array[parent])
{
swap(array[h],array[parent]);
h = parent;
parent = (h - 1) / 2;
}
}
//向堆插入新的节点
void HeapInsert(int * array,int & len,int value)
{
len++;
Heap_Increase_Key(array,len,len-1,value);
}
//维持堆函数
void KeepHeap(int * array,int len,int h)
{
int lagest = h;
int leftchild = (h << 1) + 1;//注意移位操作符的优先级低
int rightchild = (h << 1) + 2;
if (leftchild < len && array[h] < array[leftchild])
{
lagest = leftchild;
}
if (rightchild < len && array[lagest] < array[rightchild])
{
lagest = rightchild;
}
if (lagest == h)
{
return;
}
else
{
std::swap(array[h],array[lagest]);
KeepHeap(array,lagest);
}
}
//建堆函数
void MakeHeap(int * array,int len)
{
if (array == NULL || len <= 1)
{
return;
}
int k = (len - 1) >> 1;
for (auto i = k; i >= 0; --i)//利用keepheap建堆
{
KeepHeap(array,i);
}
}
//弹出堆顶函数
void Pop(int * array,int len)
{
std::swap(array[len - 1],array[0]);
KeepHeap(array,len - 1,0);
}
void HeapSort(int * array,int& len)
{
MakeHeap(array,len);
Heap_Increase_Key(array,3,5);
HeapInsert(array,0);
for (auto i = len; i > 1; --i)
{
Pop(array,i);
}
}
int main()
{
int array[15] {3,2,4,1};
int len = 4;
HeapSort(array,len);
return 0;
}