PAT 1061Insert or Merge (25)

来源:互联网 发布:英剧四级一部 知乎 编辑:程序博客网 时间:2024/05/16 00:56

题目

1061 Insert or Merge (25)

解题思路

  • 1.其实这种题不记得这些排序了根据题目也可以做出来。
  • 2.判断。如果是插入排序,则要求找到一个数比后面的数大后,那么就证明这个数后面的都没排好续,如题目中1 2 3 7 8 5 9 4 6 0,这里8>5,那么后面的数都没排序,则都和原来的相同,否则将不是插入排序。
  • 3.输出。Merge排序的下一步要注意一下,具体看代码。

代码

#include<iostream>#include<vector>#include<algorithm>using namespace std;int init[100+5], then[100+5];int main(){    int n;    cin >> n;    //vector<int> init(n), then(n);    for (int i = 0; i < n; ++i) {        cin >> init[i] ;    }    for (int i = 0; i < n; ++i) {        cin >> then[i] ;    }    //找到小于它的那个数    int m = 0;    for (; m < n; ++m) {        if (then[m] > then[m+1]) {            break;        }    }    bool isInsertion = true;    //如果m后面的数,都与原来的相同则是插入排序,否则不是    for (int i = m + 1; i < n; ++i) {        if (init[i] != then[i]) {            cout << "Merge Sort" << endl;            isInsertion = false;            break;        }    //这里小心犯错//        else {//            cout<<"Insertion Sort" << endl;//            break;//        }    }//排序(下一步)并输出,k是为了Merge排序用到的    int k = 1;    if (isInsertion) {        cout << "Insertion Sort" <<endl;        sort(then,then + m + 2);    }    else {        while (2 * (m + 1) * k<= n) {            sort(then + 2 * (m + 1) * (k - 1) , then + 2 * (m + 1) * k);            k ++;        }    }    //输出    for (int i = 0; i < n; ++i) {       //cout << then[i];        if (i) {            cout << " " << then[i];        }        else            cout<<then[i];    }    cout << endl;    return 0;}
0 0
原创粉丝点击