输入一个原始序列,一个排序后的序列,确定其是插入排序还是堆排序
此题是取出最大值后再下滤的结果
输入样例:
10
3 1 2 8 7 5 9 4 6 0
6 4 5 1 0 3 2 7 8 9
输出样例:
Heap Sort
5 4 3 1 0 2 6 7 8 9
#include<stdio.h>
#include<stdlib.h>
#define MAX 101
int b[MAX];
void swap(int*a,int*b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int match(int a[],int b[],int n)
{
for(int i=0;i<n;i++)
if(a[i]!=b[i])
return 0;
return 1;
}
int insert_sort(int a[],int n)
{
int i,j,temp,flag=0;
for(i=1;i<n;i++)
{
temp=a[i];
for(j=i;j>0&&a[j-1]>temp;j--)
a[j]=a[j-1];
a[j]=temp;
if(match(a,b,n))
{
flag=1;
int x=i+1,y;
temp=a[x];
for(y=x;y>0&&b[y-1]>temp;y--)
b[y]=b[y-1];
b[y]=temp;
break;
}
}
return flag;
}
void print(int b[],int N)
{
int i;
for(i=0;i<N-1;i++)
printf("%d ",b[i]);
printf("%d\n",b[i]);
}
void percdown(int a[],int p,int n)
{
int tmp=a[p];
int parent,child;
for(parent=p;parent*2+1<n;parent=child)
{
child=parent*2+1;
if(child<n-1&&a[child]<a[child+1])
child++;
if(a[child]>tmp) a[parent]=a[child];
else break;
}
a[parent]=tmp;
}
int heapsort(int a[],int n)
{
int i;
for(i=n/2-1;i>=0;i--)
percdown(a,i,n);
for(i=n-1;i>0;i--)
{
swap(&a[0],&a[i]);
percdown(a,0,i);
if(match(a,b,n))
{
swap(&b[0],&b[i-1]);
percdown(b,0,i-1);
return 1;
}
}
return 0;
}
int main()
{
int i,N;
scanf("%d",&N);
int a[N],c[N];
for(i=0;i<N;i++)
scanf("%d",&a[i]);
for(i=0;i<N;i++)
c[i]=a[i];
for(i=0;i<N;i++)
scanf("%d",&b[i]);
if(insert_sort(a,N)==1)
printf("Insertion Sort\n");
else if(heapsort(c,N)==1)
printf("Heap Sort\n");
print(b,N);
return 0;
}