1.合并两个有序数组成为一个有序数组

25 阅读1分钟
public class MergeTwoArray {

    public static void main(String[] args) {
        int[] a = {1,2,4,6,15};
        int[] b = {3,5,6,10,12,20};
        int[] c = mergeTwoArray(a,b);
        System.out.println(Arrays.toString(c));
    }

    private static int[] mergeTwoArray(int[] a, int[] b) {
        int[] result = new int[a.length + b.length];
        int i=0,j=0,k=0;

        while(i<a.length && j < b.length){
            if(a[i]<b[j]){
                result[k++] = a[i++];
            }else {
                result[k++] = b[j++];
            }
        }

        //把剩下的那个数组数据搬迁
        while (i<a.length){
            result[k++] = a[i++];
        }
        while (j<b.length){
            result[k++] = b[j++];
        }
        return result;
    }
}