#include<cstdio> #include<iostream> #include<vector> #include<algorithm> using namespace std; void heapAdjust(vector<int>&H, int st, int end) { int tmp; tmp = H[st]; int j; for (j = 2 * st; j <= end; j++) { if (j<end&&H[j] < H[j + 1])//这里切记防止越界 { j++; } if (tmp>=H[j])//st元素位置合法 { break; } else { H[st] = H[j]; st = j; } } H[st] = tmp;//没有子节点的话肯定合法 } void heapSort(vector<int>&H) { int i; int len = H.size(); for (i = len / 2; i >= 0; i--) { heapAdjust(H, i, len - 1); } for (i = len - 1; i >= 0; i--) { swap(H[i], H[0]); heapAdjust(H, 0, i - 1); } } int main() { vector<int>vt; //vt.push_back(1); //vt.push_back(5); //vt.push_back(2); //vt.push_back(9); //vt.push_back(7); int i; for (i = 100; i >= 0; i--) { vt.push_back(i); } heapSort(vt); for (i = 0; i < vt.size(); i++) { cout << vt[i]<<' '; } }