此题的亮点在于判断是否是插入排序或者是归并排序后要输出下一趟排序的序列。
锻炼插入排序与归并排序的代码
#include <iostream>
#include <algorithm>
using namespace std;
int ori[101], temp[101], target[101], n;
bool same(int a[]){
for(int i = 0; i < n; i++){
if(a[i] != target[i])
return false;
}
return true;
}
void showArray(int a[]){
for(int i = 0; i < n; i++){
cout << a[i];
if(i != n - 1)
cout << " ";
else
cout << endl;
}
}
bool isInsertionSort(){
bool flag = false;//记录是否与目标数组相同
for(int i = 1; i < n; i++){
if(i != 1 && same(temp)){
flag = true;
}
int j = i;
while(j > 0 && temp[j] < temp[j - 1]){
swap(temp[j], temp[j-1]);
j--;
}
if(flag)
return true;
}
return false;
}
void isMergeSort(){
bool flag = false;
for(int step = 2; step / 2 <= n; step *= 2){
if(step != 2 && same(ori)){
flag = true;
}
for(int i = 0; i < n; i += step){
sort(ori + i, ori + min(i + step, n));
}
if(flag){
cout << "Merge Sort\n";
showArray(ori);
return;
}
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i++){
cin >> ori[i];
temp[i] = ori[i];
}
for(int i = 0; i < n; i++){
cin >> target[i];
}
if(isInsertionSort()){
cout << "Insertion Sort\n";
showArray(temp);
}else{
isMergeSort();
}
return 0;
}