Recently read a book on a face question, the original topic is that there are two increments array A1 A2, A1 memory space is long enough, now requires merging A2 to A1, and requires the least number of moves, we try to interview
The most efficient way to accomplish this is the O (n) solution to the problem.
///merge void Mergearray (int *arra1,int *arra2,int nlena1,int nLenA2) {if (!arra1| |! ARRA2) return; The combined trailing int *pbehanda1= (ARRA1+NLENA1-1+NLENA2); int *pfronta1=arra1+nlena1-1; int *penda2= arra2+nlena2-1; Number of cycles N or only a second array for (int i=nlena1+nlena2,j=nlena2,k=nlena1; i>0; i--) {if (j>0&&k>0) {//When A2 is greater than A1 if (*penda2>=*pfronta1) {*pbehanda1=*penda2; penda2--; j--; }//When A2 is less than A1 else if (*penda2<*pfronta1) {*pbehanda1=*pfronta1; pfronta1--; k--; }}//End else if (j<=0) {break; }//When the previous array is merged, else if (k<=0&&j>0) {*pbehanda1=*penda2; penda2--; j--; } pbehanda1--; }}
Test code
int *p1=new int[100]; p1[0]=10; p1[1]=40; p1[2]=60; p1[3]=70; p1[4]=80; p1[5]=90; p1[6]=99; int *p2=new int[100]; p2[0]=3; p2[1]=7; p2[2]=9; p2[3]=11; p2[4]=21; p2[5]=22; p2[6]=33; Mergearray (p2,p1,7,7); for (int i=0;i<14;i++) { cout<<p2[i]<< " "; } cout<<endl;
Results
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The algorithm ordered array merging---in the case of sufficient space, the O (n) is combined and the number of moves is minimal