这个和那个合并两个有序链表类似
eg:
int[]a1={1,5,6,2,4,10,11}; 第一个区间[1,5,6]第二个区间[2,4,10,11]
合并到原数组:[1, 2, 4, 5, 6, 10, 11]
解法一:
public static void merge1(int[]a1,int i,int iEnd,int j,int jEnd,int[]a2){int index=0;while(i<=iEnd&&j<=jEnd){if(a1[i]<=a1[j]){a2[index++]=a1[i++];}else{a2[index++]=a1[j++];}}while(i<=iEnd){a2[index++]=a1[i++];}while(j<=jEnd){a2[index++]=a1[j++];}for(int k=0;k<a2.length;k++){a1[k]=a2[k];}}
解法二:
public static void merge(int[]a1,int i,int iEnd,int j,int jEnd,int[]a2,int k){if(i>iEnd){System.arraycopy(a1,j,a2,k,jEnd-j+1);//递归调用 merge 方法会导致递归深度增加,对于较大的数组,可能会导致栈溢出(StackOverflowError)。return;}if(j>jEnd){System.arraycopy(a1,i,a2,k,iEnd-i+1);return;}if(a1[i]<a1[j]){a2[k]=a1[i];merge(a1, i+1, iEnd, j, jEnd, a2, k+1);}else{a2[k]=a1[j];merge(a1, i, iEnd, j+1, jEnd, a2, k+1);}}