public static int[] arrayMerge(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;
}

例如,如果一个数组是'[16,13,15,18]',另一个数组是'[29,36,100,9]',返回的数组应该是'[9,13,15,16,29,36,100]'。

代码说明:

  1. 首先创建一个新的数组 result,其长度为两个输入数组长度之和。
  2. 使用三个索引变量 i, j, k 分别指向 a 数组,b 数组和 result 数组。
  3. 循环遍历两个输入数组,比较当前元素的大小,将较小的元素放入 result 数组中,并将对应的索引变量加一。
  4. 当一个数组遍历完后,将另一个数组剩余的元素直接放入 result 数组中。
  5. 最后返回 result 数组。
Java 数组合并排序:升序返回合并后的数组

原文地址: https://www.cveoy.top/t/topic/mMit 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录