【发布时间】:2019-09-03 18:50:20
【问题描述】:
我正在尝试创建一个方法,该方法接受两个已排序的 int 数组并返回一个新数组,该数组在不使用排序函数的情况下合并和重新排序这两个列表。我在我的循环中遇到问题,我不知道如何解决它。
我目前遇到错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at pack8.Assignment8Code.merge(Assignment8Code.java:20)
at pack8.Assignment8Code.main(Assignment8Code.java:39)
代码如下:
public class Assignment8Code
{
public static int[] merge(int[] arr1, int[] arr2)
{
//Create the first two arrays with testing numbers
arr1 = new int[5];
arr2 = new int[3];
//Create a new array that will fit the length of the two given arrays
int[] sortedArray = new int[(arr1.length + arr2.length)];
//Create starting index values to check all arrays and merge
int index1 = 0;
int index2 = 0;
//Test to see if the given arrays are populated
while(index1 < arr1.length || index2 < arr2.length)
{
//Check to see which array starts with the higher number
if(arr1[index1] < arr2[index2])
{
sortedArray[index1] = arr1[index1];
index1++;
}
else
{
sortedArray[index2] = arr2[index2];
index2++;
}
}
return sortedArray;
}
}
【问题讨论】:
-
为什么要立即丢弃参数?删除这两个
new int语句。 ---while(index1 < arr1.length || index2 < arr2.length)表示即使其中 一个 结束,您也会继续。那么你为什么没想到if(arr1[index1] < arr2[index2])在结束时会失败呢?如果两个输入都有要比较的值,则只能比较这两个值。 -
您还需要在输出数组中保留一个单独的索引,而不是使用
index1或index2。 -
@Kevin 或使用 index1 + index2
标签: java arrays sorting merge mergesort