1.堆排序
void sift(vector<int> &arr, int low, int high) { int i = low, j = 2 * i; int temp = arr[i]; while (j <= high) { if (j < high && arr[j] < arr[j + 1]) { j++; } if (temp < arr[j]) { arr[i] = arr[j]; i = j; j = 2 * i; } else { break; } } arr[i] = temp; } void heapSort(vector<int> &arr) { int n = arr.size() - 1; if (n <= 1) { return; } for (int i = n / 2; i >= 1; i--) { sift(arr, i, n); } for (int i = n; i >= 2 ; i--) { swap(arr[1], arr[i]); sift(arr, 1, i - 1); } }
测试用例:
有效排序元素从1开始
vector<int> arr = {0, 3, 2, 4, 1, 7, 6 }; heapSort(arr);