用java实现两个数组合并
时间: 2024-05-02 21:18:46 浏览: 54
以下是使用Java实现合并两个数组的示例代码:
```java
public class MergeArrays {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] mergedArray = mergeArrays(array1, array2);
System.out.println(Arrays.toString(mergedArray));
}
public static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] mergedArr = 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]) {
mergedArr[k++] = arr1[i++];
} else {
mergedArr[k++] = arr2[j++];
}
}
while (i < arr1.length) {
mergedArr[k++] = arr1[i++];
}
while (j < arr2.length) {
mergedArr[k++] = arr2[j++];
}
return mergedArr;
}
}
```
输出结果为:[1, 2, 3, 4, 5, 6]
阅读全文