A1089 Insert or Merge [再理解非递归的归并排序]

在这里插入图片描述
题目大意:给一串数组a和排序中的数组b,要你判断是什么排序,并且给出当前排序的下一次排序样子。
解题重点:

  1. 这一次对于插入排序和归并排序的迭代形式有了更深的理解。
  2. 这里要可视化每一步的数字,所以要用归并排序的非递归形式,非递归形式注意一趟归并中要把最后两个子列单独讨论,因为最后可能不满足有左右两个子列,如果只有左子列直接数组赋到结果后面,如果存在就归并所有的。
  3. 数组后面new一个就不必要每次开一个数组,节省空间,记得用完释放。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<time.h>
using namespace std;
const int maxn = 100; int n;
bool judge(int a[], int b[], int n)
{
	for (int i = 0; i < n; i++)
		if (a[i] != b[i])
			return false;
	return true;
}
bool insertSort(int a[],int b[], int n)
{
	int i, j;
	for (i = 1; i < n; i++)
	{
		int tem = a[i];
		for (j = i; j >=1&&a[j-1]>tem; j--)
		{
				a[j] = a[j-1];		
		}
		a[j] = tem;
		if (judge(a, b, n))
		{
			i++;
			tem = a[i];
			for (j = i; j >= 1 && a[j - 1] > tem; j--)
			{
				a[j] = a[j - 1];
			}
			a[j] = tem;
			return true;
		}
	}
	return false;
}
void merge(int a[],int temp[],int l1, int r1, int l2, int r2)
{
	int i = l1, j = l2;
	int index = 0;
	while (i <= r1 && j <= r2)
	{
		if (a[i] <= a[j])
			temp[index++] = a[i++];
		else
			temp[index++] = a[j++];
	}
	while (i <= r1)
		temp[index++] = a[i++];
	while (j <= r2)
		temp[index++] = a[j++];
	for (i = 0; i < index; i++)
	{
		a[l1 + i] = temp[i];
	}
}
void mergePass(int a[], int temp[], int n, int length)
{
	int i;
	for (i = 0; i < n - 2 * length; i += 2 * length)
		merge(a, temp, i, i + length - 1, i + length, i + length * 2 - 1);
	if (i + length < n)
		merge(a, temp, i, i + length - 1, i + length, n - 1);
	else
		for (int j = i; j < n; j++)
			temp[j] = a[j];
}
bool mergeSort(int a[],int b[],int n) {
	int length = 1;
	int* tem = new int[n];
	if (tem != NULL) {
		while (length < n) {
			mergePass(a, tem, n, length);
			length *= 2;
			if (judge(a, b, n))
			{
				mergePass(a, tem, n, length);
				return true;
			}
		}
		return false;
		delete[] tem;
	}
	else cout << "空间不足";
}
void output(int A[], int N) {
	for (int i = 0; i < N; i++) {
		if (i)
			cout << " ";
		cout << A[i];
	}
}
int main()
{
	int n; cin >> n;
	int a[maxn], temp[maxn], b[maxn];
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
		temp[i] = a[i];
	}
	for (int i = 0; i < n; i++)
	{
		cin >> b[i];
	}
	if (insertSort(temp, b, n))
	{
		cout << "Insertion Sort" << endl;
		output(temp, n);
		return 0;
	}
	if (mergeSort(a, b, n))
	{
		cout << "Merge Sort" << endl;
		output(a, n);
		return 0;
	}
	return 0;
}
posted @ 2020-07-13 11:29  _Hsiung  阅读(65)  评论(0编辑  收藏  举报