首页 > 其他 > 详细

PAT(Advanced Level)A1098.Insertion or Heap Sort

时间:2020-10-31 23:49:49      阅读:32      评论:0      收藏:0      [点我收藏+]

题意

给定一个序列和几次迭代后的序列,问能否判断出是属于插入排序or堆排序。要求判断后输出对应方法的下一次迭代的序列

思路

  • 区分插入排序和归并排序的要点在于:插入排序总是会使得前几个元素有序,而堆排序是后几个有序,而且堆本身是左小右大,所以我们只要比较前2个元素的大小关系就知道是哪一种了
  • 插入排序的下一次迭代就是让前面的有序小区间长度+1,所以找到第一个不符合有序的定义来处理就好,这里可以用sort()函数少写点代码

代码

#include <cstdio>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
const int MAXN = 110;
int heap[MAXN];     //存储第二个序列
int N;
int origin[MAXN];
void insert_sort(int a[])
{
    int pos = 1;
    for(int i=1;i<=N;i++)
    {
        if(a[i] > a[i+1])
        {
            pos = i + 1;
            break;
        }
    }
    sort(a + 1, a + pos + 1);
}//插入排序
void downAdjust(int heap[], int low, int high)
{
    int i = low, j = i * 2;
    while(j <= high)
    {
        if(j + 1 <= high && heap[j + 1] > heap[j])
            j = j + 1;
        if(heap[j] > heap[i])
        {
            swap(heap[j], heap[i]);
            i = j;
            j = i * 2;
        }else break;
    }
}//向下调整
void heap_sort(int heap[])
{
    int pos = 1;
    for(int i=N;i>=1;i--)
        if(heap[i] < heap[1])
        {
            pos = i;
            swap(heap[1], heap[pos]);
            break;
        }
    downAdjust(heap, 1, pos - 1);
}//堆排序
int main()
{
    cin >> N;
    for(int i=1;i<=N;i++)    cin >> origin[i];
    for(int i=1;i<=N;i++)    cin >> heap[i];
    if(heap[1] < heap[2])   //插入排序
    {
        insert_sort(heap);
        cout << "Insertion Sort\n";
        for(int i=1;i<=N;i++)
            i == N ? cout << heap[i] : cout << heap[i] << " ";
    }else{
        heap_sort(heap);
        cout << "Heap Sort\n";
        for(int i=1;i<=N;i++)
            i == N ? cout << heap[i] : cout << heap[i] << " ";
    }
    return 0;
}

PAT(Advanced Level)A1098.Insertion or Heap Sort

原文:https://www.cnblogs.com/MartinLwx/p/13907091.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!