参考自柳诺https://www.liuchuo.net/
#include <iostream> #include <algorithm> using namespace std; int main(){ //输入 int a[110],b[100]; int n; cin >> n; for(int i = 0;i < n;i++){ cin >> a[i]; } for(int i = 0;i < n;i++){ cin >> b[i]; } //判断是否是插入算法,归并不好直接判断 int pos = 0; for(int i = 0;i < n - 1;i++){ //找到 if(b[i] > b[i+1]){ pos = i; break; } } int j = pos + 1; while(j < n && a[j] == b[j])j++; if(j == n){ cout << "Insertion Sort" << endl; sort(a,a + pos + 2); //下一轮应排序到[0,pos + 1].一共(pos + 2)个元素 }else{ cout << "Merge Sort" << endl; int flag = 1,k = 1; while(flag){ flag = 0; for(int i = 0;i < n;i++){ //对a[]进行归并排序,直到和b[]相等为止 if(a[i] != b[i]) flag = 1; } k = k * 2; //归并的步长,每次x2 for(int i = 0;i < n / k;i++){ //k被n整除部分 sort(a + i * k,a + (i + 1) * k); } sort(a + n/k * k,a + n); //余下部分 } for(int i = 0;i < n;i++){ //上边while()里边,满足相等条件后又排序了一次,所以直接输出即可 if(i != 0)cout << " "; cout << a[i]; } } return 0; }
柳诺的代码
#include <iostream> #include <algorithm> using namespace std; int main() { int n, a[100], b[100], i, j; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; for (i = 0; i < n - 1 && b[i] <= b[i + 1]; i++) ; for (j = i + 1; a[j] == b[j] && j < n; j++) ; if (j == n) { cout << "Insertion Sort" << endl; sort(a, a + i + 2); } else { cout << "Merge Sort" << endl; int k = 1, flag = 1; while (flag) { flag = 0; for (i = 0; i < n; i++) { if (a[i] != b[i]) flag = 1; } k = k * 2; for (i = 0; i < n / k; i++) sort(a + i * k, a + (i + 1) * k); sort(a + n / k * k, a + n); } } for (j = 0; j < n; j++) { if (j != 0) printf(" "); printf("%d", a[j]); } return 0; }