算法的内容见算法导论堆排序章节
#include <iostream>
using namespace std;
struct Heap{
int *data;
int dateLength;//堆中的数据元素的个数
int heapLength;//进行堆运算的元素的个数
};
int Parent(int i){//i节点对应的父节点
return i/2;
}
int Left(int i){//i节点对应的左孩子
return 2*i;
}
int Righ(int i){//i节点对应的右孩子
return 2*i+1;
}
void InitHeap(int n,Heap *hp){//初始化一个含有n个元素的堆
hp->data=new int[n+1];
hp->dateLength=n;
hp->heapLength=1;
int i;
for (i=1;i<=hp->dateLength;i++)
{
cin>>hp->data[i];
}
}
void MaxHeapify(Heap *hp,int i){//对堆中的节点i进行 向下递归操作,维持堆的性质
int l,r;
l=Left(i);
r=Righ(i);
int largest;
if (l<=hp->heapLength && hp->data[l]>hp->data[i] )
{
largest=l;
}else{
largest=i;
}
if (r<=hp->heapLength && hp->data[r]>hp->data[largest])
{
largest=r;
}
if (largest!=i)
{
int temp=hp->data[largest];
hp->data[largest]=hp->data[i];
hp->data[i]=temp;
MaxHeapify(hp,largest);
}
}
void BuildMaxHeap(Heap *hp){//建立一个大堆
hp->heapLength=hp->dateLength;
int i;
for (i=hp->dateLength/2;i>=1;i--)
{
MaxHeapify(hp,i);
}
}
void HeapShow(Heap *hp);//显示堆中的数据元素
void HeapSort(Heap *hp){//进行堆排序
BuildMaxHeap(hp);
HeapShow(hp);
int temp;
for (int i=hp->dateLength;i>=2;i--)
{
//swap
temp=hp->data[hp->heapLength];
hp->data[hp->heapLength]=hp->data[1];
hp->data[1]=temp;
hp->heapLength--;
MaxHeapify(hp,1);
}
}
int HeapMaxMum(Heap *hp){//返回大堆中的最大元素的值
return hp->data[1];
}
int HeapExtractMax(Heap *hp){//移除堆中的最大元素
int max=hp->data[1];
hp->data[1]=hp->data[hp->heapLength];
hp->heapLength--;
MaxHeapify(hp,1);
return max;
}
void HeapIncreaseKey(Heap *hp,int i,int key){//将大堆中的第i个元素的值增加到 key.并维持大堆性质
if (key<hp->data[i])
{
return ;
}
hp->data[i]=key;
int temp;
while (i>1 && hp->data[Parent(i)]<hp->data[i])
{
//swap
temp=hp->data[Parent(i)];
hp->data[Parent(i)]=hp->data[i];
hp->data[i]=temp;
i=Parent(i);
}
}
void MaxHeapInsert(Heap *hp,int key){//向大堆中添加值为key 的数据元素
//
if (hp->heapLength==hp->dateLength)
{
//overflow
return ;
}
hp->heapLength++;
hp->data[hp->heapLength]=0x8000;//the most min integer
HeapIncreaseKey(hp,hp->heapLength,key);
}
void HeapShow(Heap *hp){
int i;
for (i=1;i<=hp->dateLength;i++)
{
cout<<hp->data[i]<<" ";
}
cout<<endl;
}
int main(int argc,char *argv[]){
Heap *hp=new Heap;
InitHeap(5,hp);
BuildMaxHeap(hp);
HeapShow(hp);
HeapIncreaseKey(hp,3,6);
HeapShow(hp);
return 0;
}