//留神为不便操作,堆的下标从1开始const int maxn = 100;int heap[maxn], n = 10;//向下调整void downAdjust(int low, int high){ int i = low, j = 2*i; while(j <= high){ if(j + 1 <= high && heap[j+1] > heap[j]){//此处不要遗记判断j+1是否超过了high j = j+1; } if(heap[i] < heap[j]){ swap(heap[i], heap[j]); i = j; j = 2*i; }else{ break; } }}//建堆void createHeap(){ for(int i = n/2; i >= 1; i--){ downAdjust(i, n); }}//删除堆顶元素void delTop(){ heap[1] = heap[n--]; downAdjust(1, n); //此处前面的是n,因为n曾经自减了}//向上调整void upAdjust(int low, int high){ int i = high, j = i/2; while(j >= low){ if(heap[i] > heap[j]){ swap(heap[i], heap[j]); i = j; j = i/2; }else{ break; } }}//增加元素void insert(int x){ heap[++n] = x; upAdjust(1, n);}//堆排序void heapSort(){ createHeap(); for(int i = n; i > 1; i--){//从后往前倒着枚举替换 swap(heap[1], heap[i]); downAdjust(1, i-1); }}