java如何用一个循环实现两个有序数组合并成一个有序数组

如题,代码如下:

public void paixu() {
        int[] a = { 1, 3, 5 };
        int[] b = { 2, 3, 4, 7 };
        int l = a.length + b.length;
        int[] temp = new int[l];
        int i = 0, j = 0, h = 0;
        // 这里必须用while,不能用for
        while (i < a.length || j < b.length) {
            if (i == a.length && j < b.length) {
                temp[h++] = b[j++];
            } else if (i < a.length && j == b.length) {
                temp[h++] = a[i++];
            } else if (a[i] <= b[j]) {
                temp[h++] = a[i++];
            } else if (a[i] > b[j]) {
                temp[h++] = b[j++];
            }
        }
        for (int m : temp) {
            System.out.print(m + "  ");
        }
    }

猜你喜欢

转载自www.cnblogs.com/yinyl/p/12322377.html