import org.junit.Test;import java.util.Arrays;public class MergeSort {/*** @param A: sorted integer array A* @param B: sorted integer array B* @return: A new sorted integer array* <p>* 合并排序数组 II* 合并两个排序的整数数组A和B变成一个新的数组。* <p>* 样例* 给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]* <p>* 挑战* 你能否优化你的算法,如果其中一个数组很大而另一个数组很小?*/public int[] mergeSortedArray(int[] A, int[] B) {// write your code hereint i = A.length;int j = B.length;int x = 0;int y = 0;int[] C = new int[i + j];int k = 0;while (x < i && y < j) {if (A[x] <= B[y]) {C[k++] = A[x++];} else {C[k++] = B[y++];}}while (x < i) {C[k++] = A[x++];}while (y < j) {C[k++] = B[y++];}return C;}@Testpublic void testMergeSortedArray() {int[] A = {23, 4, 2, 34, 2, 34, 32};int[] B = {6, 245, 3, 234, 2, 46, 23, 45, 23423, 3, 4, 23};System.out.println(Arrays.toString(A));System.out.println(Arrays.toString(B));System.out.println(Arrays.toString(mergeSortedArray(A, B)));}
}
转载于:https://www.cnblogs.com/wei1/p/9582062.html