【SSL】1271排序I

【SSL】1271排序I

Time Limit:1000MS
Memory Limit:65536K

Description

输入n(<=100000),由小到大输出

Input

n
n个数

Output

由小到大输出

Sample Input

5
3 2 1 4 5

Sample Output

1 2 3 4 5

思路

用小根堆。
建堆后堆排序。
输出根节点,删除根节点,最后一个数上移

代码

#include<iostream>
#include<cstdio>
using namespace std;
int h[100010];
class heapmn
{
	private:
	public:
		void heapup(int n,int x);//上移操作,把h[x]上移的合适位置
		void heapdown(int n,int x);//下移操作,把h[x]下移的合适位置
		void heapinsert(int &n,int x);//插入操作,把x加入堆的合适位置 
		void heapdelete(int &n,int x);//删除操作,删除h[x]
		void heapsort(int &n);//堆排序 
		void heapbuild(int &n,int m);//建堆 
		void swap(int &t1,int &t2);//交换两数
};
void heapmn::swap(int &t1,int &t2)//交换两数 
{
	int t=t1;
	t1=t2,t2=t;
	return;
}
void heapmn::heapup(int n,int x)//上移操作,把h[x]上移的合适位置 
{
	if(x>n)return;
	for(;x>1;x>>=1)
		if(h[x]<h[x>>1]) swap(h[x],h[x>>1]);
		else return;
	return;
}
void heapmn::heapdown(int n,int x)//下移操作,把h[x]下移的合适位置
{
	if(x<1)return;
	for(x<<=1;x<=n;x<<=1)
	{
		x+=(x+1<=n&&h[x+1]<h[x]);
		if(h[x]<h[x>>1]) swap(h[x>>1],h[x]);
		else return;
	}
	return;
}
void heapmn::heapinsert(int &n,int x)//插入操作,把x加入堆的合适位置 
{
	h[++n]=x;
	heapup(n,n);
	return;
}
void heapmn::heapdelete(int &n,int x)//删除操作,删除h[x] 
{
	if(h[n]<=h[x]) h[x]=h[n--],heapup(n,x);
	else h[x]=h[n--],heapdown(n,x);
	return;
}
void heapmn::heapsort(int &n)//堆排序 
{
	for(;n;h[1]=h[n--],heapdown(n,1))
	{
		//a[i]=h[1];
		printf("%d ",h[1]);
	}
	return;
}
void heapmn::heapbuild(int &n,int m)//建堆 
{
	int i;
	for(n=0,i=1;i<=m;i++)
	{
	    //h[++n]=a[i];
		scanf("%d",&h[++n]);
	    heapup(n,n);
	}
	return;
}
int main()
{
	heapmn heap;
	int n;
	scanf("%d",&n);
	heap.heapbuild(n,n);
	heap.heapsort(n);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值