PAT 甲級 刷題日記|A 1089 Insert or Merge (25 分)

思路

考察經(jīng)典的排序算法

判斷merge的下一輪 沒有一個很好的特征作為條件,直接去模擬的思路非常妙!

代碼

#include <bits/stdc++.h>
using namespace std;

const int maxn = 105;
int ori[maxn], aft[maxn];

int main() {
    int n;
    cin>>n;
    for (int i = 0; i < n; i++) {
        cin>>ori[i];
    }
    for (int i = 0; i < n; i++) {
        cin>>aft[i];
    }
    int q = 1;
    while (aft[q] >= aft[q - 1] && q < n) q++;
    int k = q;
    while (ori[q] == aft[q] && q < n) q++;

    if (q == n) {
        cout<<"Insertion Sort"<<endl;
        if (k == n) k--;
        sort(aft, aft + k + 1);
        for (int i = 0; i < n; i++) {
            cout<<aft[i];
            if (i != n - 1) cout<<" ";
            else cout<<endl;
        }
    } else {
        cout<<"Merge Sort"<<endl;
        k = 1;
        int flag = 0;
        while (1) {
            for (int i = 0; i < n; i += (k * 2)) {
                int t = min(i + 2 * k, n);
                sort(ori + i, ori + t);
            }
            if (flag == 1) break;
            int j;
            if (flag == 0) {
                for (j = 0; j < n; j++) {
                    if (ori[j] != aft[j]) break;
                }
                if (j == n) flag = 1;
            }
            k *= 2;
        }
        for (int i = 0; i < n; i++) {
            cout<<ori[i];
            if (i != n - 1) cout<<" ";
            else cout<<endl;
        }   
    }
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容