堆排序_最大優先佇列
阿新 • • 發佈:2019-02-18
//maxPriorityQueue.cpp //優先佇列支援的操作:insert ,maximum,extract,increaseKey, #include <iostream> #include <ctime> #include <cstdlib> #define NUMBER 100 #define NUM 6 using 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; }