1089. Insert or Merge (25)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;

#define N 100

int main(int argc, char **argv) {
	int n;
	cin >> n;

	int a[2][N] = {{}};
	for(int i = 0; i < 2; i ++) {
		for(int j = 0; j < n; j ++) {
			cin >> a[i][j];
		}
	}
	int pos = 1;
	for(; pos < n; pos ++) {
		if(a[1][pos] < a[1][pos-1])
			break;
	}

	bool insert = true;
	for(int i = pos; i < n; i ++) {
		if(a[0][i] != a[1][i]) {
			insert = false;
			break;
		}
	}

	if(insert) {
		int tmp = a[1][pos];
		int i = pos;
		for(; i > 0; i --) {
			if(a[1][i-1] > tmp) {
				a[1][i] = a[1][i-1];
			}
			else
				break;
		}
		a[1][i] = tmp;
	}
	else {
		bool sorted = true;
		int step = 1;
		do  {
			step *= 2;
			for(int i = 0; i < n && sorted; i += step) {
				for(int j = 1; j < step && i+j < n; j ++) {
					if(a[1][i+j-1] > a[1][i+j]) {
						sorted = false;
						break;
					}
				}
			}
		} while(sorted) ;

		for(int i = 0; i < n; i += step) {
			int a1 = i, a2 = i+step/2;
			int tmp[N] = {};
			int count = 0;
			while((a1 < i+step/2 && a1 < n) || (a2 < i+step && a2 < n)) {
				if(a1 >= i+step/2 || a1 >= n) {
					tmp[count ++] = a[1][a2 ++];
				}
				else if(a2 >= i+step || a2 >= n) {
					tmp[count ++] = a[1][a1 ++];
				}
				else {
					if(a[1][a1] <= a[1][a2])
						tmp[count ++] = a[1][a1 ++];
					else
						tmp[count ++] = a[1][a2 ++];
				}
			}
			for(int j = 0; j < count; j ++) {
				a[1][i+j] = tmp[j];
			}
		}
	}

	printf("%s\n", insert ? "Insertion Sort" : "Merge Sort");
	printf("%d", a[1][0]);
	for(int i = 1; i < n; i ++) {
		printf(" %d", a[1][i]);
	}
	putchar('\n');

	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值