本文实例为大家分享了c++实现两个有序数组合并的具体代码,供大家参考,具体内容如下
剑指提供面试题5延展题:
问题:有两个排序的数组A1和A2,内存在A1的末尾有足够多的空间容纳A2。请实现一个函数,把A2中所有数字插入A1中,并且所有的数字是排序(默认升序)的。
<>强思路:强>在合并两个数组(包括字符串)时,从前往后复制每个数字(或字符)则需要重复移动数字(或字符)多次,则考虑从后往前复制就可以减少移动的次数,从而提高效率。
1。n1、n2分别指向数组A1和A2的尾部,strNew指向合并后的数组的尾部;
2.当数组名是一个nullptr指针,或者A1数组是一个空数组则返回;
3 .当数组A1 (ida)祝辞=A2 (idb)或者idb<0时,则复制ida指针所指的数到strNew指向的位置,ida向前移动1格,strNew向前移动1格;
4 .当数组A1 (ida) & lt; A2 (idb)或者ida<0时,则复制idb指针所指的数到strNew指向的位置,idb向前移动1格,strNew向前移动1格;
5 .直到strNew<0则停止循环。
<强>注意:强>
输入的n1、n2为数组的长度,作指针时都要1;
循环终止的条件从合并数组指针入手,合并结束循环终止,即strNew<0;
注意形参和实参的传递,数组传入函数的三种声明func (int * arr), func (int arr [n]), func (int[]的arr),返回数组指针的函数int * func ()
# include# include 使用名称空间性病; int *插入(int, int * str2 int * str1 n1, int n2, int长度){//int * dest=str1; 如果(str1==nullptr | | str2==nullptr | | & lt;长度=0){ 返回0; } int strNew=n1 + n2 - 1; int ida=n1-1; int idb=n2-1; 而(strNew祝辞=0){ 如果(str1 (ida)祝辞=str2 (idb) | | idb<0) { str1 [strNew——]=str1 (ida); 艾达-; } else if (str1 (ida) & lt;str2 (idb) | | ida<0) { str1 [strNew——]=str2 (idb); idb -; } } 返回str1;//返回桌子; } int main () { int n1、n2; ,,cin>的在n1>的在n2; int (n1)、b (n2); for (int i=0;i 在b[我]; }//int * c;//c=插入(a, b, n1、n2 100); 插入(a, b, n1、n2 100); for (int i=0; i< n1 + n2; + + i) { cout<& lt;[我]& lt; & lt; ' '; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。