#include
#include
/*
func: 合并两个有序数组
arrSrc:将另外一有序数组arrDest合并至该数组
arrDest:将该数组合并至另外一有序数组arrSrc
captionSrc:arrSrc的容量大小,保证能保存arrSrc + arrDest
lenSrc:arrSrc数组的现有有效元素个数
lenDest:arrDest数组的现有有效元素个数
*/
void mergeArray(int* arrSrc, int* arrDest,int captionSrc,int lenSrc, int lenDest)
{
if(NULL == arrSrc || NULL == arrDest || ((lenSrc + lenDest) > captionSrc)) {
return;
}
int indexOfNew = lenSrc + lenDest - 1; //新数组的末位索引
int indexOfSrc = lenSrc - 1;//arrSrc有效元素的末位索引
int indexOfDest = lenDest - 1;//arrDest有效元素的末位索引
//当arrDest所有扫描完成,元素所有插入arrSrc,剩余arrSrc元素不须要移位操做
//当arrSrc所有遍历完成,但arrDest仍有元素时,只须要操做arrDest便可,此时arrSrc下标已达最小值0
while (indexOfDest >= 0) {
if (indexOfSrc >= 0){
//将arrSrc或arrDest中较大的元素放入arrSrc新位置,同时移动变化数组的指针位置
if (arrSrc[indexOfSrc] >= arrDest[indexOfDest]) {
arrSrc[indexOfNew] = arrSrc[indexOfSrc];
--indexOfNew;
--indexOfSrc;
}else{
arrSrc[indexOfNew] = arrDest[indexOfDest];
--indexOfNew;
--indexOfDest;
}
} else {
arrSrc[indexOfNew] = arrDest[indexOfDest];
--indexOfNew;
--indexOfDest;
}
}
}
int main(void)
{
int arrSrc[100] = {1,1,1,1,1,1,3,5,7,9};
int arrDest[6] = {2,4,6,8,10,12};
mergeArray(arrSrc, arrDest, 100, 10, 6);
printf("after merge ,arrSrc is:\n");
for(int i = 0; i < 16; ++i) {
printf("%d ",arrSrc[i]);
}
printf("\n");
return 0;
}