堆排序_最大优先队列

来源:互联网 发布:手机淘宝能开网店么 编辑:程序博客网 时间:2024/06/06 10:44
//maxPriorityQueue.cpp//优先队列支持的操作:insert ,maximum,extract,increaseKey,#include <iostream>#include <ctime>#include <cstdlib>#define NUMBER 100#define NUM 6using namespace std;struct heapType{int heapArray[NUMBER];int arraySize;int heapSize;};void exchange(int *,int *);void maxHeapify(heapType &,int);void buildMaxHeap(heapType &);int heapMaximum(heapType &h);//返回h中具有最大关键字的元素void insert(heapType &h,int x);//将元素x插入到集合h中使之仍然组成最大堆int heapExtractMax(heapType &h);//去掉,并返回h中具有最大关键字的元素//将元素i关键字增加到k,void heapIncreaseKey(heapType &h,int i,int k);void print(heapType &h);int main(){heapType heap;heap.arraySize = NUM;heap.heapArray[0] = 0;srand(unsigned(time(NULL)));for(int i=1;i<=heap.arraySize;i++)heap.heapArray[i] = rand()%101;cout << "the array is :" << endl;print(heap);cout << "build the max heap:" << endl;buildMaxHeap(heap);cout << "the heap is :" << endl;print(heap);cout << "get the maximum :" << heapMaximum(heap) << endl;cout << "add a number :90" << endl;insert(heap,90);cout << "the heap is :" << endl;print(heap);cout << "change the 5th number into 8." << endl;heapIncreaseKey(heap,5,8);cout << "the heap is :" << endl;print(heap);cout << "delete the maximum number :" << heapExtractMax(heap) << endl;cout << "the heap is :" << endl;print(heap);system("pause >> cout");return 0;}void exchange(int *x,int *y){int temp = *x;*x = *y;*y = temp;}//最大堆的性质void maxHeapify(heapType &h,int i){int l = 2*i;int r = 2*i + 1;int subscript = i;if(l<=h.heapSize && h.heapArray[subscript]<h.heapArray[l])subscript = l;if(r<=h.heapSize && h.heapArray[subscript]<h.heapArray[r])subscript = r;if(subscript!=i){cout << "echange the " << i << "th :" << h.heapArray[i]        << " and the " << subscript << "th :" << h.heapArray[subscript]    << endl;exchange(&h.heapArray[subscript],&h.heapArray[i]);maxHeapify(h,subscript);}}//建堆void buildMaxHeap(heapType &h){h.heapSize = h.arraySize;for(int i=h.heapSize/2;i>=1;i--)maxHeapify(h,i);}//返回h中具有最大关键字的元素int heapMaximum(heapType &h){return h.heapArray[1];}//去掉,并返回h中具有最大关键字的元素int heapExtractMax(heapType &h){if(h.heapSize<1){cout << "heap underflow" << endl;return -1;}int max = h.heapArray[1];h.heapArray[1] = h.heapArray[h.heapSize];h.heapSize = h.arraySize = h.arraySize - 1;maxHeapify(h,1);return max;}//将元素i关键字增加到k,void heapIncreaseKey(heapType &h,int i,int k){h.heapArray[i] = k;for(int j=i;j>=1;j=j/2)maxHeapify(h,j);}//将元素x插入到集合h中使之仍然组成最大堆void insert(heapType &h,int x){h.arraySize = h.arraySize + 1;h.heapSize = h.arraySize;h.heapArray[h.heapSize] = 0;heapIncreaseKey(h,h.heapSize,x);}void print(heapType &h){for(int i=1;i<=h.arraySize;i++){cout << " " << h.heapArray[i];if(i%20==0)cout << endl;}cout << endl;}

0 0