#include <iostream>
using namespace std;
void mergeArray(int *A1,int& length1, int*A2, int length2)//把A2合併到A1中,假設A1,A2中的元素是從小到大
{
if(A1==NULL || A2==NULL || length1<0 || length2<0) return;
int p1 = length1-1, p2 = length2-1;
length1 += length2;
int p = length1-1;
while(p2>=0 && p1>=0)
{
A1[p--] = A1[p1]>A2[p2]?A1[p1--]:A2[p2--];
}
while(p2>=0)
{
A1[p--] = A2[p2--];
}
/*while(p1>=0) //可不寫
{
A1[p--] = A2[p1--];
}*/
}
int main()
{
int* a = new int[5];
int lena = 2;
a[0] = 2;a[1] = 7;
int b[] = {3,8};
mergeArray(a,lena,b,2);
for(int i=0;i<lena;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
《劍指offer》面試題4(合併數組)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.