您的位置:首页 > 其它

合并两个排序的数组

2015-01-15 21:47 197 查看
1.问题描述

有俩个排序的数组A1,A2,内存在A1的末尾有足够多的空余空间容纳A2,请实现一个函数,把A2中所有的数字插入到A1中并且所有的数字是排序的。(来自《剑指offer》)

2.分析

其实和之前写的一道替换空格的程序类似,都是数组的从后向前遍历的例子。这道题也同样,从前向后复制每个数字需要重复移动数字多次,从后向前复制可以减少移动次数,从而提高效率。

3.代码

void MerageArray(int *a1,int *a2,int a1Length,int a2Length,int a1Volume)
{
int merageLength = a1Length + a2Length;

//边界检查
if (!a1 || !a2 || merageLength > a1Volume ||
a1Length <= 0 || a2Length <= 0)
{
return;
}

int index   = merageLength-1; //用来指向a1或a2中元素要被复制到的位置

int a1Index = a1Length-1; //指向a1中要复制元素的位置

int a2Index = a2Length-1;//指向a2中要复制元素的位置

while (index >= 0 && a1Index >= 0 && a2Index >= 0)
{
if(a1[a1Index] > a2[a2Index])
{
a1[index] = a1[a1Index];

a1Index--;
}
else
{
a1[index] = a2[a2Index];

a2Index--;
}

index--;
}

while (index >= 0 && a1Index >= 0)
{
a1[index] = a1[a1Index];

index--;

a1Index--;
}

while (index >= 0 && a2Index >= 0)
{
a1[index] = a2[a2Index];

index--;

a2Index--;
}

}


此题同样是提醒大家遍历数组时,考虑一下从后向前遍历是否对要解决的问题能高效些。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: