[英]How to merge and print two sorted arrays of ints
我正在嘗試創建一個方法,該方法接收兩個已排序的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;
}
}
您的代碼中存在多個問題:
merge
方法中分配arr1
和arr2
會使其失敗。 以下是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整數),從而對垃圾收集器造成不必要的壓力。 對整個mergesort使用單個臨時數組會更有效,但需要不同的merge
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.