A1089(插入排序与归并排序过程中的判断)

此题的亮点在于判断是否是插入排序或者是归并排序后要输出下一趟排序的序列。
锻炼插入排序与归并排序的代码

#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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值