首页 > 编程语言 > 详细

堆排序

时间:2017-10-30 16:52:54      阅读:217      评论:0      收藏:0      [点我收藏+]

//建堆

#include <cstdio>
#include <iostream>
using namespace std;
int n,a[110];

void update(int o){
	int l=o<<1,r=o<<1|1,maxn;
	if(l<=n && a[l]>a[o])maxn=l;
	else maxn=o;
	if(r<=n && a[r]>a[maxn])maxn=r;
	if(maxn!=o){
		swap(a[o],a[maxn]);
		update(maxn);
	}
}

void init(){
	for(register int i=n/2;i;i--)update(i);
}

int main(){
	scanf("%d",&n);
	for(register int i=1;i<=n;i++)scanf("%d",&a[i]);
	init();
	for(register int i=1;i<=n;i++)printf("%d ",a[i]);
	return 0;
}

  

堆排序

原文:http://www.cnblogs.com/codetogether/p/7755023.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!