#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int N;
bool isInsertion(int initial[], int partially[]){
bool sorted = true;
for(int i = 0; i < N; i++){
if(i && partially[i] < partially[i - 1])
sorted = false;
if(!sorted && partially[i] != initial[i])
return false;
}
return true;
}
int getIndex(int partially[]){
for(int i = 0; i < N; i++)
if(i && partially[i] < partially[i - 1])
return i;
return N;
}
int getStep(int partially[]){
int current_step = 0, max_step = 100;
for(int i = 0; i < N; i++){
current_step ++;
if(i && partially[i] < partially[i - 1]){
max_step = min(current_step, max_step);
current_step = 1;
}
}
int result = 1;
while(max_step > result * 2)
result *= 2;
return result;
}
int main()
{
int initial[101], partially[101];
cin>>N;
for(int i = 0; i < N; i++)
cin>>initial[i];
for(int i = 0; i < N; i++)
cin>>partially[i];
bool is_insertion = isInsertion(initial, partially);
if(is_insertion){
int insertion_index = getIndex(partially);
sort(partially, partially + insertion_index + 1);
}
else{
int merge_step = getStep(partially) * 2;
for(int i = 0; i < N; i += merge_step)
sort(partially + i, partially + min(i + merge_step, N));
}
cout<<(is_insertion?"Insertion Sort":"Merge Sort")<<endl;
for(int i = 0; i < N; i ++){
if(i) cout<<" ";
cout<<partially[i];
}
}
用LUA(和C++)刷PAT (Advanced Level) ——1089 Insert or Merge
该博客探讨了一种智能选择插入排序和归并排序的方法。根据输入数组的状态,如果已部分排序,则使用插入排序;否则,采用分块归并排序策略。算法首先检查数组是否已排序,然后确定最佳插入点或计算归并步长,以实现高效排序。最终,展示了如何在C++中实现这一过程。
摘要由CSDN通过智能技术生成