有两个排序的数组A1和A2,内存在A1的末尾有足够多余的空间容纳A2。
请实现一个函数,把A2中的所有数字插入到A1中,并且所有数字是排序的.
思路:从末尾到头比较A1和A2中的数字,并把较大的数字复制到A1中的合适位置
/**
*有两个排序的数组A1和A2,内存在A1的末尾有足够多余的空间容纳A2。
*请实现一个函数,把A2中的所有数字插入到A1中,并且所有数字是排序的.
*
*思路:从末尾到头比较A1和A2中的数字,并把较大的数字复制到A1中的合适位置
*/
#include <iostream>
void mergeSortArray(int *a1, const int& length1,
const int* a2, const int& length2)
{
int length = length1+length2;
//指向合并后数字的结尾
int i2 = length-1;
//指向合并前a1的结尾
int i1 = length1-1;
//指向a2数组的结尾元素
int j = length2-1;
while (i1 >= 0 && j >=0)
{
if (a1[i1] > a2[j])
{
a1[i2] = a1[i1];
--i1;
}
else
{
a1[i2] = a2[j];
--j;
}
--i2;
}
/*
// 将剩余的a1的元素copy a1的合并数组中
// 没有必要做
while (i1 >= 0)
{
a1[i2--] = a1[i1--];
}
*/
//将剩余的a2中的元素copy到合并的a1中
while (j >= 0)
{
a1[i2--] = a2[j--];
}
}
/**
* test1:a1数组比a2短
* a1[9, 20]
* a2[2, 4, 6, 11]
* test2: a1数组比a2长
* a1[1, 3, 5, 9, 20]
* a2 [2, 4, 11]
* test3: a1数字与a2一样长
* a1[1, 3, 5, 7]
* a2[2, 4, 6, 8]
*/
int main(int argc, char* argv[])
{
int a1[100] = {1, 3, 5, 7};
int length1 = 4;
int a2[] = {2, 4, 6, 8};
int length2 = sizeof(a2)/sizeof(a2[0]);
// std::cout << "length2 : " << length2 << std::endl;
mergeSortArray(a1, length1, a2, length2);
int length = length1+length2;
for (int i = 0; i < length; i++)
std::cout << a1[i] << " ";
std::cout << std::endl;
return 0;
}