不稳定 O(nlogn)
#include <iostream>
using namespace std;
void FindMaxInHeap(int arr[], const int size) { //使堆顶始终最大
for (int j = size - 1; j > 0; --j) {
int parent = j / 2;
int child = j;
if (j < size - 1 && arr[j] < arr[j+1]) {
++child;
}
if (arr[child] > arr[parent]) {
int tmp = arr[child];
arr[child] = arr[parent];
arr[parent] = tmp;
}
}
}
void HeapSort(int arr[], const int size) {
for (int j = size; j > 0; --j) { //循环使数组尾部存储最大的数
FindMaxInHeap(arr, j);
int tmp = arr[0];
arr[0] = arr[j - 1];
arr[j - 1] = tmp;
}
}
int main() {
int arr[] = {10, 2, 3, 5, 4, 78, 56, 9, 87, 10};
int n = sizeof(arr) / sizeof(arr[0]);
HeapSort(arr, n);
for (int j = 0; j < n; ++j) {
cout << arr[j] << ", ";
}
cout << endl;
}