堆排序:
以下内容是我根据其他资料和博客整理写出来的堆排序(降序),如有问题,欢迎提出。
#include <iostream>
#include <algorithm>
using namespace std;
int a[15000];
void minheapify(int a[],int n,int i) {//维护最小堆的性质;
int l = 2 * i;
int r = 2 * i + 1;
int minest;
if (l <= n && a[l] < a[i]) minest = l;
else minest = i;
if (r <= n && a[r] < a[minest]) minest = r;
if (i != minest) {
int t = a[i];
a[i] = a[minest];
a[minest] = t;
minheapify(a,n,minest);
}
}
void buildminheap(int a[],int n) {//建立最小堆;
for (int i = n / 2;i >= 1;--i) {
minheapify(a,n,i);
}
}
void heapsort(int a[],int n) {//堆排序(降序) 原理:最小堆的性质;
buildminheap(a,n);
int size = n;
for (int i = n;i >= 2;--i) {
swap(a[1],a[i]);
size--;
minheapify(a,size,1);
}
}
int main() {
int n;
cin >> n;
for (int i = 1;i <= n;++i) cin >> a[i];
heapsort(a,n);
for (int i = 1;i <= n;++i) cout << a[i] << " ";
cout << endl;
return 0;
}