归并两个有序数组

来源:互联网 发布:牙齿填骨粉的利弊 知乎 编辑:程序博客网 时间:2024/05/19 19:13

           题目:有两个有序的数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2。请实现一个函数,把A2中的所有数字插入到A1中并且所有的数字是排序的。

       解法:从后向前依次比较处理,减少移动次数,提高效率。

void SortA1A2(int A1[],int length1,int sizeofA1,int A2[],int length2){if(A1==NULL||A2==NULL||length1<=0||length2<=0||sizeofA1<=0)return;if(sizeofA1<length1+length2)return;int newlength1=length1+length2-1;int plen1=length1-1;int plen2=length2-1;while (plen1>=0&&plen2>=0){if(A1[plen1]>=A2[plen2])    A1[newlength1--]=A1[plen1--];else    A1[newlength1--]=A2[plen2--];    }while (plen2>=0){A1[newlength1--]=A2[plen2--];}return;}int _tmain(int argc, _TCHAR* argv[]){const int length = 100;int length1=5;int length2=5;int A1[length] = {1,3,5,7,9};int A2[] = {2,4,6,8,10};int A3[] ={12,14,16,18,20};for(int i=0;i<length1;i++){cout<<A1[i]<<"  ";}for(int i=0;i<length2;i++){cout<<A2[i]<<"  ";}SortA1A2(A1,length1,length,A2,length2);for(int i=0;i<length1+length2;i++){cout<<A1[i]<<"  ";}    return 0;}



参考:剑指offer 面试题4后扩展

0 0
原创粉丝点击