Java 数组合并:升序排序算法实现
以下是 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;
}
该程序的实现思路是首先创建一个长度为两个数组长度之和的新数组 result,然后使用三个指针 i、j 和 k 分别指向数组 a、b 和 result 的当前位置。接着,通过比较 a[i] 和 b[j] 的大小,将较小的元素放入 result 数组中,并将相应指针向前移动一位,直到其中一个数组被遍历完毕。最后,将剩余的元素按顺序放入 result 数组中,返回合并后的升序数组 result。
示例:
假设一个数组是 {16, 13, 15, 18},另一个数组是 {29, 36, 100, 9},返回的数组应该是 {9, 13, 15, 16, 29, 36, 100}。
原文地址: https://www.cveoy.top/t/topic/mMdg 著作权归作者所有。请勿转载和采集!