PAT1098 Insertion or Heap Sort

题目链接:

http://www.nowcoder.com/pat/5/problem/4322

题目大意:

判断插入排序还是堆排序。

首先判断下是哪种排序,是则以此排序方式再迭代一步。

代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int dest[105];
int N;
int flag;
bool isEqual(int* sort)
{
    for (int i = 0; i < N; i++)
    {
        if (sort[i] != dest[i])
        {
            return false;
        }
    }
    return true;
}
void Insertion_Sort(int* sort,int N)
{
    for (int i = 1; i < N; i++)
    {
        int tmp = sort[i];
        int j;
        for (j = i; j>0 && sort[j - 1] >= tmp; j--)
        {
            sort[j] = sort[j - 1];
        }
        sort[j] = tmp;
        if (flag == 1)
        {
            return;
        }
        if (isEqual(sort))
        {
            flag = 1;
        }
    }

}
void PercDown(int* sort,int parent,int n)
{
    int child;
    int tmp = sort[parent];
    for (; parent * 2+1 <= n-1; parent = child)
    {
        child = parent * 2+1;
        if (child != n-1 && sort[child] < sort[child + 1])
        {
            child++;
        }
        if (tmp >= sort[child])
        {
            break;
        }
        else
        {
            sort[parent] = sort[child];
        }
    }
    sort[parent] = tmp;
}
void swap(int* a,int* b)
{
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}
void Heap_Sort(int* sort,int N)
{
    for (int i = N / 2; i >= 0; i--) //调成最大堆
    {
        PercDown(sort,i,N);
    }
    for (int i = N - 1; i >= 0; i--)
    {
        swap(&sort[0],&sort[i]);
        PercDown(sort,0,i);
        if (flag == 2)
        {
            return;
        }
        if (isEqual(sort))
        {
            flag = 2;
        }
    }
}
int main()
{
    int init[105];
    int insertionSort[105];
    int heapSort[105];

    flag = 0;
    scanf("%d",&N);
    for (int i = 0; i < N; i++)
    {
        scanf("%d",&init[i]);
    }
    for (int i = 0; i < N; i++)
    {
        scanf("%d",&dest[i]);
    }
    for (int i = 0; i < N; i++)
    {
        insertionSort[i] = heapSort[i] = init[i];
    }
    Insertion_Sort(insertionSort,N);
    Heap_Sort(heapSort,N);
    if (flag == 1)
    {
        printf("Insertion Sort\n");
        printf("%d", insertionSort[0]);
        for (int i = 1; i < N; i++)
        {
            printf(" %d",insertionSort[i]);
        }
    }
    else if (flag == 2)
    {
        printf("Heap Sort\n");
        printf("%d", heapSort[0]);
        for (int i = 1; i < N; i++)
        {
            printf(" %d", heapSort[i]);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值