堆的各種操作:
用數組來表示堆,i結點的父結點就為(i–1) / 2。它的左右子結點下標分別為2 * i + 1和2 * i + 2。如第0個結點左右子結點下標分別為1和2。
void max_heapify(int[],int); //保持堆的性質
void buid_max_heap(int []); //建堆
void max_heap_sort(int []); //堆排序
int heap_maximum(int[]); //返回最大值
void max_heap_increase(int[],int i,int key); //使第i個元素的值增加到key
void max_heap_insert(int [],int key); //把元素key插入到堆中
int max_heap_extarct_max(int[]); //去掉並返回A中最大的元素
#include<iostream>using namespace std;int heap_size; //堆的大小 int n; //數組A中元素的個數 n<=1000 void max_heapify(int[],int);void buid_max_heap(int []);void max_heap_sort(int []); //堆排序int heap_maximum(int[]); //返回最大值void max_heap_increase(int[],int i,int key); //使第i個元素的值增加到key void max_heap_insert(int [],int key); //把元素key插入到堆中 int max_heap_extarct_max(int[]); //去掉並返回A中最大的元素 int main(){int A[1000]; //堆的最大容量為1000 cin>>n; heap_size=n; for(int i=0;i<n;i++) cin>>A[i];buid_max_heap(A);cout<<"堆中的最大元素為"<<heap_maximum(A);cout<<endl;int a;cout<<"請輸入一個元素,這個元素將插入到堆中:";cin>>a;max_heap_insert(A,a);cout<<"插入"<<a<<"之後的堆為:";for(int i=0;i<n;i++)cout<<A[i]<<" ";cout<<endl;cout<<"堆中的最大元素為:"<<max_heap_extarct_max(A)<<",將其去掉。";cout<<"\n去掉最大元素之後的堆為:";for(int i=0;i<n;i++)cout<<A[i]<<" ";cout<<endl;cout<<"請輸入一個元素號,和想要增加到的key:";int e_num,key;cin>>e_num>>key; while(e_num>=n||key<=A[e_num]){cout<<"輸入錯誤,請重新輸入:";cin>>e_num>>key;}max_heap_increase(A,e_num,key);cout<<"將第"<<e_num<<"號元素增加到"<<key<<"之後的堆為:";for(int i=0;i<n;i++)cout<<A[i]<<" ";cout<<endl;max_heap_sort(A); cout<<"堆排序,結果為:";for(int i=0;i<n;i++)cout<<A[i]<<" ";cout<<endl;getchar(); }void max_heapify(int A[],int i){int l=i*2+1;int r=i*2+2;int largest;if(l<heap_size&&A[l]>A[i])largest=l;else largest=i;if(r<heap_size&&A[r]>A[largest])largest=r;if(largest!=i){swap(A[i],A[largest]);max_heapify(A,largest);}}void buid_max_heap(int A[]){heap_size=n;for(int i=(n-1)/2;i>=0;i--)max_heapify(A,i); //堆從(len-1)/2到0都是非葉子結點 } void max_heap_sort(int A[]){buid_max_heap(A);for(int i=n-1;i>=1;i--){swap(A[0],A[i]); //現在A[i]就是最大值 heap_size--;max_heapify(A,0);}}int heap_maximum(int A[]){return A[0];} void max_heap_increase(int A[],int i,int key){A[i]=key;while(i>0&&A[(i-1)/2]<A[i]){swap(A[i],A[(i-1)/2]);i=(i-1)/2;}}void max_heap_insert(int A[],int key){A[heap_size]=-9999999; //負無窮 max_heap_increase(A,heap_size,key);n++;heap_size++;}int max_heap_extarct_max(int A[]){if(heap_size<1) cout<<"heap overflow!"<<endl;else{int max=A[0];A[0]=A[heap_size-1];heap_size--;max_heapify(A,0);return max;} }
結果: