pat 乙级c++ 插入与归并 (25分)

确认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;
}

转载须注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值