09-排序3 Insertion or Heap Sort

输入一个原始序列,一个排序后的序列,确定其是插入排序还是堆排序
此题是取出最大值后再下滤的结果

输入样例:
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值