堆排序
1 /** 2 * 排序算法之堆排序 3 **/ 4 #include <iostream> 5 #include <cstdio> 6 #include <cstring> 7 #include <algorithm> 8 #include <vector> 9 using namespace std; 10 11 void adjust(vector<int>& vec, int len, int index) { 12 int left = 2 * index + 1; 13 int right = 2 * index + 2; 14 int maxIdx = index; //代表父子三个数中最大数的下标 15 if (left < len && vec[left] > vec[maxIdx]) maxIdx = left; 16 if (right < len && vec[right] > vec[maxIdx]) maxIdx = right; 17 if (maxIdx != index) { 18 swap(vec[maxIdx], vec[index]); 19 adjust(vec, len, maxIdx); 20 } 21 22 } 23 24 void heapSort(vector<int>& vec, int size) { 25 for (int i = size / 2 - 1; i >= 0; i--) {//从最后一个非叶节点开始进行堆调整 26 adjust(vec, size, i); 27 } 28 29 for (int i = size - 1; i >= 1; i--) { 30 swap(vec[0], vec[i]); 31 adjust(vec, i, 0); 32 } 33 34 } 35 36 int main() { 37 vector<int> vec = {2,1,3,5,4}; 38 int len = vec.size(); 39 heapSort(vec, len); 40 for (auto x : vec) { 41 cout << x << endl; 42 } 43 return 0; 44 }