#include <iostream>
#include <vector>
using namespace std;
//堆化
void heapify(vector<int>& arr, int n, int i) {
int largest = i; //初始化为最大根
int left = 2 * i + 1; //左子节点
int right = 2 * i + 2; //右子节点
//如果左子节点大于根
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
//如果右子节点大于根
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
//如果最大不是根
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
//堆排序
void heapSort(vector<int>& arr) {
int n = arr.size();
//从最后一个非叶子结点构建堆
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
//排序
for (int i = n - 1; i >= 0; i--) {
swap(arr[i], arr[0]);
heapify(arr, i, 0);
}
}
void printarr(vector<int>& nums) {
for (auto n : nums) {
cout << n << " ";
}
cout << endl;
}
int main() {
vector<int> arr = { 12, 11, 13, 5, 6, 7 };
printarr(arr);
heapSort(arr);
printarr(arr);
return 0;
}