AcWing 838. 堆排序
原题链接
简单
作者:
DoIdo
,
2020-04-14 23:50:39
,
所有人可见
,
阅读 687
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e6 + 10;
int u[maxn];
void heapify(int* tree, int n, int i) {
if (i >= n + 1) return;
int c1 = 2 * i;
int c2 = 2 * i + 1;
int mx = i;
if (c1 <= n && tree[c1] > tree[mx]) {
mx = c1;
}
if (c2 <= n && tree[c2] > tree[mx]) {
mx = c2;
}
if (mx != i) {
swap(tree[i], tree[mx]);
heapify(tree, n, mx);
}
}
void build_heap(int* tree, int n) {
int father = n / 2;
for (int i = father; i >= 1; i--) {
heapify(tree, n, i);
}
}
void heap_sort(int* tree, int n) {
build_heap(tree, n);
for (int i = n; i >= 1; i--) {
swap(tree[i], tree[1]);
heapify(tree, i - 1, 1);
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> u[i];
}
heap_sort(u, n);
for (int i = 1; i <= m; i++) {
cout << u[i] << " ";
}
return 0;
}