帮我写一个java代码合并2个数组使其有序
时间: 2024-05-09 14:16:55 浏览: 62
好的,这是一个合并两个有序数组的Java代码:
```
public static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] merged = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < arr1.length) {
merged[k++] = arr1[i++];
}
while (j < arr2.length) {
merged[k++] = arr2[j++];
}
return merged;
}
```
该方法接收两个已排序的数组,并返回一个合并的有序数组。
使用该函数示例:
```
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
int[] merged = mergeArrays(arr1, arr2);
// 打印合并后的数组
for (int i = 0; i < merged.length; i++) {
System.out.print(merged[i] + " ");
}
```
运行后的输出为:
```
1 2 3 4 5 6
```
阅读全文