这篇文章主要介绍了C语言实现在数组A上有序合并数组B的方法,包含了数组操作的完整实现过程以及相应的代码分析与改进,具有不错的借鉴价值,需要的朋友可以参考下
本文实例讲述了C语言实现在数组A上有序合并数组B的方法,分享给大家供大家参考。具体分析如下:
题目:数组A和数组B均有序,数组A有足够大内存来容纳数组B,将数组B有序合并到数组A中
分析:如果由前至后合并,复杂度将会是O(N2),这样的复杂度显然不是最优解,利用两个指针指向两个数组的尾部,从后往前遍历,这样的复杂度为O(n2)
由此可以写出下面的代码:
#include #include #include 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 && posB >= 0) { if (arrayA[posA] (cout, " ")); system("pause"); } return arrayA; } void main() { int *result = mergeArray(arrayA, size<i style="color:transparent">来源gaodai$ma#com搞$$代**码网</i>A, arrayB, sizeB); copy(result, result + 10, ostream_iterator(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 && posB >= 0) { if (arrayA[posA] (cout, " ")); system("pause"); } //出现两种情形: //1. posA = 0 //2. posA >= 0 && posB = 0) { while (posB >= 0) { arrayA[posA + posB + 1] = arrayB[posB]; posB--; } } return arrayA; }
相信本文所述对大家C程序算法设计的学习有一定的借鉴价值。
以上就是C语言实现在数组A上有序合并数组B的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!