#include <cstdlib> #include <iostream> #include <algorithm> #include <ctime> using namespace std; const int MAX = 100; void filerDown(int heap[], int start, int end) { int i = start; int j = 2 * i + 1; int temp = heap[i]; while(j <= end) { if(j < end && heap[j] < heap[j + 1]) j++; if(temp >= heap[j]) break; else { heap[i] = heap[j]; i = j; j = 2 * j + 1; } } heap[i] = temp; } void createHeap(int heap[], int count) { int curSize = count; int curPos = (curSize - 2) / 2; while(curPos >= 0) { filerDown(heap, curPos, curSize - 1); curPos--; } } void heapSort(int heap[], int count) { for(int i=count - 1; i>0; i--) { swap(heap[0], heap[i]); filerDown(heap, 0, i - 1); } } int main(int argc, char *argv[]) { int heap[MAX]; int curCount = 50; srand((unsigned)time(NULL)); for(int i=0; i<curCount; i++) heap[i] = rand() % MAX; cout << "before sort: " << endl; for(int i=0; i<curCount; i++) cout << heap[i] << " "; cout << endl << "after sort: " << endl; createHeap(heap, curCount); heapSort(heap, curCount); for(int i=0; i<curCount; i++) cout << heap[i] << " "; cout << endl; system("PAUSE"); return EXIT_SUCCESS; } 如果要从大到小排序, 首先根据输入数据建立一个最大堆, 然后将heap[0]与最后一个元素交换, 再利用filerDown()调整堆使之从新成为最大堆, 在将hea[0]与倒数第二个元素交换, 在调整, 直到所有的都调整完...