[SSL] 1271 Sort I

[SSL] 1271 Sort I

Time Limit:1000MS
Memory Limit:65536K

Description

Input n (<=100000), output from small to large

Input

n
n number

Output

Output from small to large

Sample Input

5
3 2 1 4 5

Sample Output

1 2 3 4 5

Ideas

Pile with small roots.
The heap is sorted after the heap is built.
Output the root node, delete the root node, and move the last number up

Code

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

Guess you like

Origin blog.csdn.net/weixin_46975572/article/details/113113482