PAT甲级1098 Insertion or Heap Sort (25分) 堆排序 swap交换数组元素

1098 Insertion or Heap Sort (25分)
According to Wikipedia:

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Heap sort divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. it involves the use of a heap data structure rather than a linear-time search to find the maximum.

Now given the initial sequence of integers, together with a sequence which is a result of several iterations of some sorting method, can you tell which sorting method we are using?

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then in the next line, N integers are given as the initial sequence. The last line contains the partially sorted sequence of the N numbers. It is assumed that the target sequence is always ascending. All the numbers in a line are separated by a space.

Output Specification:
For each test case, print in the first line either “Insertion Sort” or “Heap Sort” to indicate the method used to obtain the partial result. Then run this method for one more iteration and output in the second line the resulting sequence. It is guaranteed that the answer is unique for each test case. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input 1:
10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0
Sample Output 1:
Insertion Sort
1 2 3 5 7 8 9 4 6 0
Sample Input 2:
10
3 1 2 8 7 5 9 4 6 0
6 4 5 1 0 3 2 7 8 9
Sample Output 2:
Heap Sort
5 4 3 1 0 2 6 7 8 9

题目就是让你区分给出的两组数列是堆排序还是插入排序,并且输出排序的下一步数列

因为是堆排序,需要用数组下表来确定孩子位置,所以数组应该从下标1开始存储

问题1:如何判断是堆排序还是插入排序
我感觉判断是不是插入排序更加简单一点,插入排序前面部分有序,后面部分不变,按照这个规律就可判断啦,我这里是按照posA 是否小于posb来判断是否是插入排序的

    int posA=1,posB=N;
    while(posA<N-1)
    {
        if(sn2[posA]<=sn2[posA+1])
            posA++;
        else
            break;
    }
    while(posB>=0)
    {
        if(sn1[posB]==sn2[posB])
        {
            posB--;
        }
        else
        {
            break;
        }
    }
    //posA<posB 就是堆排序

问题2:插入排序如何输出下一步的排序数列
可以自己模拟下一次的插入,也可以直接使用sort方法。问题一使用的变量posA指向的位置就是已排序序列最后一个元素的位置了,自己实现插入排序那就把posA+1指向的元素插入到0到posA之间。如果使用sort方法,直接一行代码sort(sn2+1,sn2+posA+2),posA+2的原因是sort算法第二个参数是数组初始地址加上需要排序数字的个数。

问题3:堆排序如何输出下一步的排序数列
这个感觉是最麻烦的,首先理解堆排序,在本题中其实只要实现堆排序的下调函数就行,初始化堆不用考虑,也是简单了点。PAT例二的推演过程如下图,字比较丑
在这里插入图片描述
然后现在其实只要实现了堆排序的下调过程,然后找到有序序列的起始位置,这个题也就搞定啦。
关于确定有序序列的起始位置我的思路是直接对原数列sort排序后,从后向前和sn2数组一个个比较,不一样了就break

        sort(sn1+1,sn1+N+1);
        int maxPos=N;
        while(sn1[maxPos]==sn2[maxPos])
        {
            maxPos--;
        }

        maxPos+=1;//指向当前已经有序的元素位置

下面是我最开始实现的下调函数

//maxpos指向已经有序的第一个数字,所以首先把maxpos-1位置的元素和1位置元素的位置互换
int cache=sn2[1];
        sn2[1]=sn2[maxPos-1];
        sn2[maxPos-1]=cache;

        maxPos-=2;//maxPos-2之后,就从1调整到maxpos位置

        int start=1;
        while(start<=maxPos)
        {

            if(start*2+1<=maxPos)
            {
                //左右孩子都调整
                int childMax=sn2[start*2]>sn2[start*2+1]?sn2[start*2]:sn2[start*2+1];
                int sign=sn2[start*2]>sn2[start*2+1]?0:1;
                if(sn2[start]<childMax)
                {
                    int cache=sn2[start];
                    sn2[start]=childMax;
                    if(sign==0)
                    {
                        sn2[start*2]=cache;
                        start*=2;
                    }

                    else
                    {
                        sn2[start*2+1]=cache;
                        start=start*2+1;
                    }

                }
                else
                    break;
            }
            else if(start*2<=maxPos) //只有左孩子
            {

                if(sn2[start]<sn2[start*2])
                {
                    int cache=sn2[start];
                    sn2[start]=sn2[start*2];

                    sn2[start*2]=cache;
                    start*=2;
                }
                else
                    break;
            }
            else
                break;
        }

之后看了柳神博客https://www.liuchuo.net/archives/2273,下调函数精简了一下

        swap(sn2[1],sn2[maxPos-1]);//确定当前下调的最大值
        maxPos-=2;//maxPos-2之后,就从1到maxpos的位置范围下调

        int start=1;
        while(start*2<=maxPos)//这里一定要是start*2 因为没有左孩子不在调整范围就不用调整了
        {
            int swapPos=start*2;//用swapPos记录左右孩子那个大
            if(start*2+1<=maxPos&&sn2[start*2]<sn2[start*2+1])
                swapPos++;//右孩子大
            if(sn2[start]<sn2[swapPos]){
                swap(sn2[start],sn2[swapPos]);
                start=swapPos;//调整后,start保存下调后的位置,再循环下调
            }
        }

整个代码

#include <iostream>
#include <algorithm>
using namespace std;


int main()
{
    int N;
    cin>>N;
    int sn1[N+1],sn2[N+1];
    for(int i=1; i<N+1; i++)
    {
        cin>>sn1[i];
    }
    for(int i=1; i<N+1; i++)
    {
        cin>>sn2[i];
    }
    //判断是否是插入排序

    int posA=1,posB=N;
    //posA指向有序序列的最后一个元素
    while(posA<N)
    {
        if(sn2[posA]<=sn2[posA+1])
            posA++;
        else
            break;
    }

    while(posB>=1)
    {
        if(sn1[posB]==sn2[posB])
        {
            posB--;
        }
        else
        {
            break;
        }
    }
    if(posA<posB)
    {
        cout<<"Heap Sort"<<endl;
        //我的想法是直接把sn1排序了,然后和sn2对比...
        sort(sn1+1,sn1+N+1);
        int maxPos=N;
        while(sn1[maxPos]==sn2[maxPos])
        {
            maxPos--;
        }

        maxPos+=1;//指向当前已经有序的元素位置

        //pos-1 就是无序序列部分的最后一个元素位置

        swap(sn2[1],sn2[maxPos-1]);
        maxPos-=2;//maxPos-2之后,就从1调整到maxpos位置

        int start=1;
        while(start*2<=maxPos)
        {
            int swapPos=start*2;
            if(start*2+1<=maxPos&&sn2[start*2]<sn2[start*2+1])
                swapPos++;
            if(sn2[start]<sn2[swapPos]){
                swap(sn2[start],sn2[swapPos]);
                start=swapPos;
            }
        }
    }
    else
    {
        cout<<"Insertion Sort"<<endl;
        //posA++;//需要把无需序列的第一个元素缓存下来
        //int cache=sn2[posA];
        //posA--;//posA指向有序序列的最后一个,一个个和cache比较,大了就后移
        //while(posA>=0&&cache<sn2[posA])
        //{
        //    sn2[posA+1]=sn2[posA];
        //    posA--;
        // }
        //sn2[posA+1]=cache;
        sort(sn2+1,sn2+posA+2);

    }

    //结果输出
    for(int i=1; i<=N; i++)
    {
        if(i==1)
        {
            cout<<sn2[i];
        }
        else
        {
            cout<<' '<<sn2[i];
        }
    }
    return 0;
}


关于堆排序的详解可以看看这个知乎文章
https://zhuanlan.zhihu.com/p/34324469

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++,如果你追求更高的性能并且确实需要对大量数据进行排序,有几种替代 `std::sort` 的选择,虽然它们不一定总是比 `std::sort` 快,但在某些特定场景下可能会有所提升: 1. **插入排序(Insertion Sort)**:对于小数组或者基本有序的数据,插入排序可能比 `std::sort` 更快。因为它的时间复杂度在最好、最坏情况下都是O(n^2),但对于近乎有序的数据,它的效率接近 O(n)。 ```cpp template<typename T> void insertion_sort(T arr[], int n) { for (int i = 1; i < n; ++i) { T key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } ``` 2. **堆排序Heap Sort)**:堆排序在大数据量下表现较好,平均时间复杂度为 O(n log n),而且它是原地排序(即不需要额外空间),适用于内存受限的情况。 ```cpp void heapify(int arr[], int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest != i) { swap(arr[i], arr[largest]); heapify(arr, n, largest); } } void heapSort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n - 1; i >= 0; i--) { swap(arr, arr[i]); heapify(arr, i, 0); } } ``` 3. **基数排序(Radix Sort)**:对于非整数数据或者数字位数较少的情况,基数排序可以达到线性时间复杂度,但它需要额外的辅助空间。 需要注意的是,每种排序方法都有其适用范围,实际选择哪种取决于具体的场景和需求。在大多数普通用途,`std::sort` 已经足够高效,只有在性能瓶颈明显的前提下,才考虑这些替代方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值