/**
* 两个有序的数组,合并成一个有序的数组
* @author ccq
*
*/
public class Test1 {
public static void main(String[] args) {
int[] a = new int[] { 1, 3, 5, 7, 8, 8, 9, 100, 111, 222 };
int[] b = new int[] { 2, 3, 4, 5, 6, 7, 8 };
int arr[] = sortArr(a, b);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
/**
* 算法复杂度O(m+n)
* m : a数组的长度
* n : b数组的长度
* @param a
* @param b
* @return arr 合并后的数组
*/
public static int[] sortArr(int[] a, int[] b) {
int sum = 0;
int aIndex = 0;
int bIndex = 0;
int arrIndex = 0;
int aLen = a.length;
int bLen = b.length;
int[] arr = new int[aLen + bLen];
while (aIndex < aLen && bIndex < bLen) {
if (a[aIndex] < b[bIndex]) {
arr[arrIndex++] = a[aIndex++];
}else if(a[aIndex] == b[bIndex]){
arr[arrIndex++] = a[aIndex++];
arr[arrIndex++] = b[bIndex++];
}else {
arr[arrIndex++] = b[bIndex++];
}
sum++;
}
for (int i = aIndex; i < aLen; i++) {
arr[arrIndex++] = a[i];
sum++;
}
for (int i = bIndex; i < bLen; i++) {
arr[arrIndex++] = b[i];
sum++;
}
System.out.println("sum = " + sum + ", a+b = " + (aLen + bLen));
return arr;
}
}