【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;
}

猜你喜欢

转载自blog.csdn.net/weixin_46975572/article/details/113113482