确认true后再执行一次的循环结构
#include <cstdio>
#include <vector>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <iostream> //用set试试
using namespace std;
int n;
bool cmp(int a,int b){
return a<=b;
}
bool isSm(vector<int> tempori, vector<int> changed, int n){
for(int i=0; i<n; i++){
if(tempori[i]!=changed[i]){
return false;
}
}
return true;
}
void showarray(vector<int> tempori,int n){
for(int i=0; i<n; i++){
printf("%d",tempori[i]);
if(i!=n-1) printf(" ");
}
}
bool insertsort(vector<int> &tempori, vector<int> changed, int n){
bool flag=false;
int temp, i, j;
for(i=1; i<n; i++){
if(i!=1 && isSm(tempori, changed, n)){
flag=true;
}
temp=tempori[i];
for(j=i;j>0 && temp<tempori[j-1];j--){
tempori[j]=tempori[j-1];
}
tempori[j]=temp;
if(flag){
return true;
}
// showarray(tempori,n);
}
return false;
}
void mergesort(vector<int> tempori, vector<int> changed, int n){
bool flag=false;
int i,j;
for(int step=2; step/2<n; step*=2){
if(step!=2 && isSm(tempori, changed, n)){
flag=true;
}
for(i=0; i<n; i+=step){
sort(tempori.begin()+i,tempori.begin()+min(i+step,n),cmp);
}
if(flag){
showarray(tempori,n);
return;
}
}
}
int main(){
vector<int> tempori;
vector<int> changed;
vector<int> origin;
int a,n;
scanf("%d",&n);
for(int i=0; i<n; i++){
scanf("%d",&a);
origin.push_back(a);
}
tempori=origin;
for(int i=0; i<n; i++){
scanf("%d",&a);
changed.push_back(a);
}
if(insertsort(tempori,changed,n)){
printf("Insertion Sort\n");
showarray(tempori,n);
}else {
tempori=origin;
printf("Merge Sort\n");
mergesort(tempori,changed,n);
}
return 0;
}
转载须注明出处。