public class ArrayMerge {
public static int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i, j, k;
i = 0;
j = 0;
k = 0;
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
result[k++] = a[i];
i++;
} else {
result[k++] = b[j];
j++;
}
}
while (i < a.length) { // a有剩余
result[k++] = a[i];
i++;
}
while (j < b.length) { // b有剩余
result[k++] = b[j];
j++;
}
return result;
}
public static void print(int[] a) {
for (int e : a) {
System.out.print(e + "\t");
}
System.out.println();
}
public static void main(String[] args) {
int[] a = { 1, 2, 8, 19 };
int[] b = { 2, 3, 9, 12, 25 };
int[] c = merge(a, b);
print(c);
}
}
把2个有序数组合并成1个有序数组
最新推荐文章于 2023-05-31 10:23:16 发布