PAT A1098(堆排序和插入排序)

#include<bits/stdc++.h>
using std::cin;
using std::cout;
using std::endl;
using std::string;
bool visit[205];
int a[205];//原始的
int b[205];//插入排序排好的
int n;
int heap[205];
int sum=1;
void insertion_sort(int x)
{
	int j;
	int temp=a[x];
	if(a[x]<a[x-1])
	{
		for(j=x-1;temp<a[j];j--)
		{
			a[j+1]=a[j];
		}
		a[j+1]=temp;
	}
}
void adjust_down(int low,int high)
{
	int i=low,j=2*i;
	while(j<=high)
	{
		if(j+1<=high&&heap[j+1]>heap[j]) j=j+1;
		if(heap[i]<heap[j])
		{
			std::swap(heap[i],heap[j]);
			i=j;
			j=2*i;
		}
		else break;
	}
}
void adjust_up(int low,int high)
{
	int i=high,j=i/2;
	while(j>=low)
	{
		if(heap[j]<heap[i])
		{
			std::swap(heap[j],heap[1]);
			i=j;
			j=i/2;
		}
		else break;
	}
}
void heap_delete()
{
	heap[1]=heap[n--];
	adjust_down(1,n);
}
void heap_insert(int v)
{
	heap[++n]=v;
	adjust_up(1,n);
}
void heap_create()
{
	for(int i=n/2;i>=1;i--)
	adjust_down(i,n);
}
void heap_sort(int i)
{
	std::swap(heap[1],heap[i]);
	adjust_down(1,i-1);
}
void windows_cmd_support_utf8(void)
{
	#ifdef WIN32
	    system("chcp 65001 & cls");
	#endif
}
inline int read()
{
	int w=1,x=0;
	char ch=getchar();
	while(ch>'9'||ch<'0')
	{
		if(ch=='-') w=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-48,ch=getchar();
	return w*x;
}
signed main(void)
{
	windows_cmd_support_utf8();
	n=read();
	for(int i=1;i<=n;i++)
	{
		a[i]=read();
		heap[i]=a[i];
	}
	for(int i=1;i<=n;i++)
	{
		b[i]=read();
	}	
	bool heap_flag=true;
	for(int i=2;i<=n;i++)
	{
		bool insert_flag=true;
		insertion_sort(i);
		for(int j=1;j<=n;j++)
		{
			if(a[j]!=b[j]) insert_flag=false;
		}
		if(insert_flag==true)
		{
			insertion_sort(i+1);
			printf("Insertion Sort\n");
			for(int k=1;k<n;k++)
			printf("%d ",a[k]);
			printf("%d\n",a[n]);
			return 0;
		}
	}
	heap_create();
	for(int i=n;i>1;i--)
	{
		bool heap_flag=true;
		heap_sort(i);
		for(int j=1;j<=n;j++)
		{
			if(heap[j]!=b[j]) heap_flag=false;
		}
		if(heap_flag==true)
		{
			heap_sort(i-1);
			printf("Heap Sort\n");
			for(int k=1;k<n;k++)
			printf("%d ",heap[k]);
			printf("%d\n",heap[n]);
			return 0;
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值