1035 插入与归并 (25 分)

TIM截图20190226200051.jpg

解题思路:

首先判断是否为插入排序的中间序列,如果不是则为归并排序

判断方法很简单,插入排序前面一定有一段序列是非递减的,而后面的序列是和原序列相同的


#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
	int n;
	cin >> n;
	int a[102], b[102];
	//原始序列
	for (int i = 0;i < n;i++) {
		cin >> a[i];
	}
	//中间序列
	for (int i = 0;i < n;i++) {
		cin >> b[i];
	}
	//判断是否是插入排序的中间序列
	bool flag = true;
	int position;
	for(int i=0;i<n;i++) {
		if (b[i] > b[i + 1]) {
			position = i + 1;
			break;
		}
	}
	for (int j = position;j < n;j++) {
		if (a[j] != b[j]) {
			flag = false;
		}
	}
	if (flag) {
		cout << "Insertion Sort"<<endl;
		/*for (int i = position;i >= 0;i--) {
			if (b[i] < b[i - 1]) {
				int m = b[i];
				b[i] = b[i - 1];
				b[i - 1] = m;
			}
		}*/
		sort(b,b+position+1, less<int>());
		int temp=0;
		for (int j = 0;j < n;j++) {
			if (temp != 0) {
				cout << ' ';
			}
			cout << b[j];
			temp++;
		}
	}
	else {
		cout << "Merge Sort"<<endl;
		//判断两个相邻非递减序列的长度,cnt1和cnt2
		int cnt1 = 1, cnt2 = 1,cnt , m = 0;
		for (int i = 1;i < n;i++) {
			if (m < 1) {
				if (b[i] >= b[i - 1]) {
					cnt1++;
				}
				else {
					m++;
				}
			}
			else {
				if (b[i] >= b[i - 1]) {
					cnt2++;
				}
				else {
					break;
				}
			}
		}
		cnt1 <= cnt2 ? cnt = cnt1 : cnt = cnt2;//取较小值
		if (2 * cnt >= n) {
			sort(b, b + n, less<int>());
		}
		else {
			int k = 1;
			for (int i = 2 * k* cnt;i <= n;i = 2 * k*cnt) {
				sort(b + 2 * (k - 1)*cnt, b + i);
				k++;
			}
			sort(b + 2 * (k - 1)*cnt, b+n);//还需对尾部进行排序,有特殊情况
		}
		int temp = 0;
		for (int j = 0;j < n;j++) {
			if (temp != 0) {
				cout << ' ';
			}
			cout << b[j];
			temp++;
		}
	}
	return 0;
}

参考博客:https://blog.csdn.net/weixin_41112564/article/details/83051051

posted @ 2019-02-26 20:05  Chance-Zou  阅读(1325)  评论(0编辑  收藏  举报