堆排序算法
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 5 using namespace std; 6 7 class Solution 8 { 9 private: 10 public: 11 void adjustHeap(int a[], int i, int length) 12 { 13 int temp = a[i]; 14 for (int k = 2 * i + 1; k < length; k = 2 * k + 1) 15 { 16 if (k + 1 < length && a[k + 1] > a[k]) 17 { 18 k++; 19 } 20 if (a[k] > temp) 21 { 22 a[i] = a[k]; 23 i = k; 24 } 25 else 26 { 27 break; 28 } 29 } 30 31 a[i] = temp; 32 } 33 34 void heapSort(int a[], int length) 35 { 36 for (int i = length / 2 - 1; i >= 0; i--) 37 { 38 adjustHeap(a, i, length); 39 } 40 41 for (int j = length - 1; j > 0; j--) 42 { 43 int temp = a[0]; 44 a[0] = a[j]; 45 a[j] = temp; 46 47 adjustHeap(a, 0, j); 48 } 49 } 50 }; 51 52 int main() 53 { 54 Solution sol; 55 56 int a[] = {2, 6, 3, 2, 7, 4, 5}; 57 sol.heapSort(a, 7); 58 59 cout << "hello" << endl; 60 61 return 0; 62 }
posted on 2021-01-08 15:51 wlqsmiling 阅读(67) 评论(0) 编辑 收藏 举报