本文实例讲述了C语言实现在数组A上有序合并数组B的方法,分享给大家供大家参考。具体分析如下:
题目:数组A和数组B均有序,数组A有足够大内存来容纳数组B,将数组B有序合并到数组A中
分析:如果由前至后合并,复杂度将会是O(N2),这样的复杂度显然不是最优解,利用两个指针指向两个数组的尾部,从后往前遍历,这样的复杂度为O(n2)
由此可以写出下面的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#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};
经过上面的测试,不难发现在边界条件用例中,代码已经不能正确运行出结果,在测试用例的驱动下,不难写出正确代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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;
}
|
相信本文所述对大家C程序算法设计的学习有一定的借鉴价值。