【PAT 甲级】A1098 Insertion or Heap Sort (25分)

把堆排序和插入排序复现一遍就好了。
不过我个人认为的一个坑点是:对插入排序的处理要格外小心,要跳过对第一个点的插入排序才有可能拿到正确的结果。
比如一个测试样例:

//Input
4
3 4 2 1
3 4 2 1
//Output
他应该输出的是
Insertion Sort
2 3 4 1
#include <bits/stdc++.h>
using namespace std;
int heap[128];
int insert[128];
int ans[128];
void downAdjust(int lo,int hi)
{
	int i=lo,j=2*i;
	while(j<=hi)
	{
		if(j+1<=hi &&heap[j+1]>heap[j])
		j=j+1;
		if(heap[i]<heap[j])
		{
			swap(heap[i],heap[j]);
			i=j;
			j=2*i;
		}
		else return;
	}
	
}
void insertionSort(int index)		//     ->
{
	int i,temp=insert[index];
	for(i=1;i<index;i++)
	if(insert[index] < insert[i])
	{
		break;
	}
	for(int j=index;j>i;j--)
	insert[j]=insert[j-1];
	insert[i]=temp;
}
void heapSort(int n)				//     <-
{
	swap(heap[1],heap[n]);
	downAdjust(1,n-1);
}
int main(void)
{
	int n,k;
	bool iflag=false,hflag=false;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&heap[i]);
		insert[i]=heap[i];
	}
	for(int i=1;i<=n;i++)
	scanf("%d",&ans[i]);
	for(int i=n/2;i>=1;i--)
	downAdjust(i,n);
	for(k=1;k<=n;k++)
	{
		bool iFlag=true,hFlag=true;
		insertionSort(k+1);
		heapSort(n-k+1);
		for(int j=1;j<=n;j++)
		{
			if(heap[j]!=ans[j]) hFlag=false;
			if(insert[j]!=ans[j]) iFlag=false;
		}
		if(hFlag)
		{
			hflag=true;break;
		}
		else if(iFlag)
		{
			iflag=true;break;
		}
	}
	if(iflag)
	{
		printf("Insertion Sort\n");
		insertionSort(k+2);
		for(int i=1;i<=n;i++)
		{
			printf("%d",insert[i]);
			if(i!=n) printf(" ");
		}
	}
	else if(hflag)
	{
		printf("Heap Sort\n");
		heapSort(n-k);
		for(int i=1;i<=n;i++)
		{
			printf("%d",heap[i]);
			if(i!=n) printf(" ");
		}
	}
} 
发布了15 篇原创文章 · 获赞 1 · 访问量 161

猜你喜欢

转载自blog.csdn.net/weixin_42278063/article/details/104672677