两个有序数组合并成一个有序数组

这是我在美团点评面试的时候 , 遇到的一个算法题
把它记录下来

public class ArrayMarge {

    private static int[] a = {1,3,5,6,8,9};

    private static int[] b = {1,6,7,11,14,19};

    public static void main(String[] args) {
        print(marge(a , b));
    }

    private static int[] marge(int[] a , int[] b){
        int [] c = 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]){
                c[k++] = a[i++];
            } else {
                c[k++] = b[j++];
            }
        }
        while(i < a.length){
            c[k++] = a[i++];
        }
        while(j < b.length){
            c[k++] = b[j++];
        }
        return c;
    }

    private static void print(int [] a ){
        for (int i:a) {
            System.out.print(i + ",");
        }
    }

}

你可能感兴趣的:(两个有序数组合并成一个有序数组)