在数组A上有序合并数组B

题目:数组A和数组B均有序,数组A有足够大内存来容纳数组B,将数组B有序合并到数组A中

分析:如果由前至后合并,复杂度将会是O(N2),这样的复杂度显然不是最优解,利用两个指针指向两个数组的尾部,从后往前遍历,这样的复杂度为O(n2)

所以很快可以写出下面的代码:

#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;

int arrayA[10] = {1, 3, 5, 7, 9};
int arrayB[] = {2, 4, 6, 8, 10};
const int sizeB = sizeof arrayB / sizeof *arrayB;
const int sizeA = sizeof arrayA / sizeof *arrayA - sizeB;

int* mergeArray(int *arrayA, int sizeA, int *arrayB, int sizeB)
{
	if (arrayA == NULL || arrayB == NULL || sizeA < 0 || sizeB < 0)
		return NULL;

	int posA = sizeA - 1;
	int posB = sizeB - 1;

	while (posA >= 0 && posB >= 0)
	{
		if (arrayA[posA] < arrayB[posB])
		{
			arrayA[posA + posB + 1] = arrayB[posB];
			posB--;
		}
		else
		{
			arrayA[posA + posB + 1] = arrayA[posA];
			posA--;
		}
		copy(arrayA, arrayA + 10, ostream_iterator<int>(cout, " "));
		system("pause");
	}

	return arrayA;
}

void main()
{
	int *result = mergeArray(arrayA, sizeA, arrayB, sizeB);

	copy(result, result + 10, ostream_iterator<int>(cout, " "));
	cout << endl;
}


代码写完后似乎完成了所需功能,但还不止于此,必须对上述代码做UT

1. 健壮性

arrayA或arrayB为空,长度小于0

2. 边界用例

arrayA为空,长度为1;arrayB不为空,长度大于1

首元素用例

const int size = 6;

int arrayA[size] = {2};
int arrayB[] = {0, 1, 1, 1, 1};

反之

const int size = 6;
int arrayA[size] = {0, 1, 1, 1, 1};
int arrayB[] = {2};

3. 正常用例:

const int size = 10;
int arrayA[size] = {1, 3, 5, 7, 9};
int arrayB[] = {2, 4, 6, 8, 10};


const int size = 10;
int arrayA[size] = {2, 4, 6, 8, 10};
int arrayB[] = {1, 3, 5, 7, 9};


const int size = 10;
int arrayA[size] = {1, 2, 3, 4, 5};
int arrayB[] = {6, 7, 8, 9, 10};


const int size = 10;
int arrayA[size] = {6, 7, 8, 9, 10};
int arrayB[] = {1, 2, 3, 4, 5};

经过上面的测试,不难发现在边界条件用例中,代码已经不能正确运行出结果,在测试用例的驱动下,不难写出正确代码

int* mergeArray(int *arrayA, int sizeA, int *arrayB, int sizeB)
{
	if (arrayA == NULL || arrayB == NULL || sizeA < 0 || sizeB < 0)
		return NULL;

	int posA = sizeA - 1;
	int posB = sizeB - 1;

	while (posA >= 0 && posB >= 0)
	{
		if (arrayA[posA] < arrayB[posB])
		{
			arrayA[posA + posB + 1] = arrayB[posB];
			posB--;
		}
		else
		{
			arrayA[posA + posB + 1] = arrayA[posA];
			posA--;
		}
		copy(arrayA, arrayA + size, ostream_iterator<int>(cout, " "));
		system("pause");
	}

	//出现两种情形:
	//1. posA < 0 && posB >= 0
	//2. posA >= 0 && posB < 0
	//只有第1种情形需要进行处理
	if (posA < 0 && posB >= 0)
	{
		while (posB >= 0)
		{
			arrayA[posA + posB + 1] = arrayB[posB];
			posB--;
		}
	} 

	return arrayA;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值