#include<iostream> #include<vector> //这里假设堆数组元素下标从0开始 voidheapify(std::vector<int>& arr, int n, int i){//下滤操作 percolate down int largest = i; // Initialize largest as root int left = 2 * i+1; // 左子节点下标 int right = 2 * i +2; // 右子节点下标
// If left child is larger than root if (left < n && arr[left] > arr[largest]) largest = left;
// If right child is larger than largest so far if (right < n && arr[right] > arr[largest]) largest = right;
// If largest is not root if (largest != i) { std::swap(arr[i], arr[largest]); // Recursively heapify the affected sub-tree heapify(arr, n, largest); } }
// 实现堆排序 voidheapSort(std::vector<int>& arr){ int n = arr.size();
// 建堆 for (int i = n / 2 - 1; i >= 0; i--)//(i=n/2-1)是因为堆数组的元素下标从零开始 heapify(arr, n, i);
// One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end std::swap(arr[0], arr[i]);
// Call max heapify on the reduced heap heapify(arr, i, 0);//注意下滤操作的数组大小为i } }
// Utility function to print an array voidprintArray(const std::vector<int>& arr){ for (int i : arr) std::cout << i << " "; std::cout << "\n"; }