#堆排序 20.09.27

堆排序

AcWing 838. 堆排序

思路

思路,我不再多赘述,别人的文章描述,让我自愧弗如……
转到:堆排序算法(图解详细流程)

#include <bits/stdc++.h>
using namespace std;
// typedef long long ll;
const int N = 1e6 + 10;
int a[N], cnt;
int m, n;

void down (int x){
	int t = x;
	if(x * 2 <= cnt && a[t] > a[x * 2]) t = x * 2;
	if(x * 2  + 1 <= cnt && a[t] > a[x * 2 + 1]) t = x * 2 + 1;
	if(t != x) swap(a[t], a[x]), down(t);
}

int main(){
// 	freopen("ttt.in", "r", stdin);
// 	freopen("ttt.out", "w", stdout);
	
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= n; i ++) scanf("%d", &a[i]);
	cnt = n;
	for(int i = n / 2; i; i --) down(i);
	
	while(m --){
		printf("%d ", a[1]);
		a[1] = a[cnt --];
		down(1);
	}

	return 0; 
}

AcWing 839.模拟堆

原文地址:https://www.cnblogs.com/yuanyulin/p/14026734.html