#include <iostream> using namespace std; //根据需求调整大小 #define SIZE 1001 int heap[SIZE]; #define swap(x, y) {x = x + y; y = x - y; x = x - y;} void fixDown(int heap[], int pos, int size){ int x = pos; if(x > size) return;//exit // 选出最大的 int l = 2 * x; int r = l + 1; int maxPos = x; if(l <= size && heap[maxPos] < heap[l]) maxPos = l; if(r <= size && heap[maxPos] < heap[r]) maxPos = r; if(maxPos != x){ //如果父节点不是最大的,进行互换,并在新的点上继续fixDown swap(heap[x], heap[maxPos]); fixDown(heap, maxPos, size); } } void fixUp(int heap[], int size, int pos){ int x = pos; int p; while(x > 1){ p = x/2; if(heap[x] > heap[p]){ swap(heap[x], heap[p]); x = p; }else return; } } void buildHeap(int heap[], int size){ for(int i = size/2; i >= 1; i--){ fixDown(heap, i, size); } } //heapSort前要先build heap void heapSort(int heap[], int size){ int oriSize = size; for(int i = 0; i < oriSize - 1; i++){ //注意不要把oriSize和size混在一起 //互换堆顶和最后一个元素,将堆顶元素放在数组最后面 swap(heap[size], heap[1]); size--; fixDown(heap, 1, size); } } int main(){ int size = 7; for(int i = 1; i <= size; i++) heap[i] = 8 - i; buildHeap(heap, size); heap[size + 1] = 8; size++; fixUp(heap, size, size); heapSort(heap, size); }
POJ3481