Java 数组合并排序:升序返回合并后的数组
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]'。
代码说明:
- 首先创建一个新的数组
result,其长度为两个输入数组长度之和。 - 使用三个索引变量
i,j,k分别指向a数组,b数组和result数组。 - 循环遍历两个输入数组,比较当前元素的大小,将较小的元素放入
result数组中,并将对应的索引变量加一。 - 当一个数组遍历完后,将另一个数组剩余的元素直接放入
result数组中。 - 最后返回
result数组。
原文地址: https://www.cveoy.top/t/topic/mMit 著作权归作者所有。请勿转载和采集!