7-4 插入排序还是归并排序 (25 分)

解析:

  • 判断是插入排序还是归并排序
    • 如果是插入排序则: 前 k 个数 是有序的 后 n - k 个数和原数组一样
    • 否则则为归并排序
  • 如果是插入排序,直接排序前k+1个数即为答案
  • 如果是归并排序,则找出现在归并数组的长度,然后进行一次归并排序

代码

#include <bits/stdc++.h>
using namespace std;
int a[1000000];
int test[1100000];
int aux[1000000];
long long ans = 0;
void merge(int a[], int L, int mid, int R)
{
    for (int k = L; k <= R; k++)
    {
        aux[k] = a[k];
    }
    int i = L;
    int j = mid + 1;
    int k = L;
    while (i <= mid && j <= R)
    {
        if (aux[i] <= aux[j])
            a[k++] = aux[i++];

        else
            a[k++] = aux[j++];
    }
    while (i <= mid)
    {
        a[k++] = aux[i++];
    }
    while (j <= R)
    {
        a[k++] = aux[j++];
    }
}

int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }

    for (int i = 0; i < n; i++)
    {
        cin >> test[i];
    }
    int k = 0;
    int flag = 1;
    for (int i = 1; i < n; i++)
    {
        if (flag == 1 && test[i - 1] > test[i])
        {
            flag = 0;
            k = i;
        }
        if (flag == 0 && a[i] != test[i])
        {
            flag = 2;
            break;
        }
    }
    if (flag == 2)
    {
        cout << "Merge Sort" << endl;
        int size = 0x3f3f3f3f;
        int cnt = 1;
        for (int i = 0; i < n - 1; i++)
        {
            if (test[i] < test[i + 1])
            {
                cnt++;
            }
            else
            {
                size = min(cnt, size);
                cnt = 1;
            }
        }

        for (int low = 0; low < n - size; low += size + size)
        {
            merge(test, low, low + size - 1, min(low + size + size - 1, n - 1));
        }
    }
    else
    {
        cout << "Insertion Sort" << endl;
        //cout<<" k"<<k<<endl;
        if (k + 1 >= n)
            k = n - 2;
        sort(test, test + k + 1);
    }

    for (int i = 0; i < n; i++)
    {
        if (i == n - 1)
            cout << test[i] << endl;
        else
            cout << test[i] << " ";
    }
    return 0;
}

posted @ 2021-12-11 16:20  kingwzun  阅读(458)  评论(0编辑  收藏  举报