java 有序数组合并

有序数组合并,例如:

数组 A=[100, 89, 88, 67, 65, 34],

      B=[120, 110, 103, 79]

合并后的结果 result=[120, 110, 103, 79, 100, 89, 88, 67, 65, 34]

程序:

import java.util.Arrays;

public class Test {

    public static void main(String[] args) {
        int[] a = { 100, 89, 88, 67, 65, 34 };
        int[] b = { 120, 110, 103, 79 };
        int a_len = a.length;
        int b_len = b.length;
        int[] result = new int[a_len + b_len];
        // i:用于标示a数组 j:用来标示b数组 k:用来标示传入的数组
        int i = 0;
        int j = 0;
        int k = 0;
        while (i < a_len && j < b_len) {
            if (a[i] >= b[i])
                result[k++] = a[i++];
            else
                result[k++] = b[j++];
        }

        // 后面连个while循环是用来保证两个数组比较完之后剩下的一个数组里的元素能顺利传入
        while (i < a_len) {
            result[k++] = a[i++];
        }

        while (j < b_len) {
            result[k++] = b[j++];
        }
        
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
        System.out.println(Arrays.toString(result));
    }
}

结果:

[100, 89, 88, 67, 65, 34]
[120, 110, 103, 79]
[120, 110, 103, 79, 100, 89, 88, 67, 65, 34]
原文地址:https://www.cnblogs.com/ouyxy/p/7257656.html