我正在尝试创建一个方法,该方法接受两个已排序的int数组,并返回一个新数组,该数组合并并重新排序两个列表,而不使用sort函数。我在循环中遇到问题,不确定如何解决。
我目前遇到错误:
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;
}
}
答案 0 :(得分:3)
您的代码中存在多个问题:
arr1
方法中分配arr2
和merge
会达到目的。这是merge
方法的更正版本:
public class Assignment8Code
{
public static int[] merge(int[] arr1, int[] arr2)
{
// Allocate a new array that will fit the length of the two given arrays
int[] sortedArray = new int[(arr1.length + arr2.length)];
int index1 = 0;
int index2 = 0;
int index3 = 0;
// Merge the sorted arrays
while (index1 < arr1.length && index2 < arr2.length)
{
//Check to see which array starts with the higher number
if (arr1[index1] <= arr2[index2])
{
sortedArray[index3++] = arr1[index1++];
}
else
{
sortedArray[index3++] = arr2[index2++];
}
}
// Append the remaining elements
while (index1 < arr1.length)
{
sortedArray[index3++] = arr1[index1++];
}
while (index2 < arr2.length)
{
sortedArray[index3++] = arr2[index2++];
}
return sortedArray;
}
}
请注意,这种方法效率很低,因为它会为每次合并分配一个新数组。对于大型数组以这种方式实现mergesort会分配大量的mmemory(log2(N)* N个整数),从而对垃圾收集器造成不必要的压力。为整个合并排序使用单个临时数组会效率更高,但需要使用不同的merge
方法。