gpt4 book ai didi

MergeSort算法中的Java IndexOutOfBoundsException

转载 作者:太空宇宙 更新时间:2023-11-04 09:38:43 27 4
gpt4 key购买 nike

我不断得到

线程“main”中出现异常 java.lang.ArrayIndexOutOfBoundsException:MergeSorter.merge(MergeSorter.java:44)、MergeSorter.sort(MergeSorter.java:16)、MergeSorter.sort(MergeSorter.java:14) 处的索引 2 超出长度 2 的范围,MergeSorter.sort(MergeSorter.java:14), MergeSorter.sort(MergeSorter.java:14)

不知道如何修复。

之后还想转换为通用。

public class MergeSorter {
////change back to generic later
///array is item
public static void sort(int[] array, int begIndx, int endIndx) {
if (array == null) {
throw new IllegalArgumentException("Item is null.");
}
if(begIndx < endIndx) {
int midIndx = (int) Math.floor((begIndx + endIndx)/2);
sort(array, begIndx, midIndx);
sort(array, midIndx + 1, endIndx);
merge(array, begIndx, midIndx, endIndx);
}
}

//Takes to sorted arrays and merges them together
///Change type of array to generic later
public static void merge(int[] array, int begIndx, int midIndx, int endIndx) {
int sizeOfLeft = midIndx - begIndx + 1;
int sizeOfRight = endIndx - midIndx;

///change to generic later
int[] leftArr = new int[sizeOfLeft + 1];
int[] rightArr = new int[sizeOfRight + 1];

//removing equal sign from loop does nothing
for(int i = 1; i <= sizeOfLeft; i++) {
leftArr[i] = array[begIndx + i - 1];
}
for( int j = 1; j <= sizeOfRight; j++) {
rightArr[j] = array[midIndx + j];
}
leftArr[sizeOfLeft + 1] = Integer.MAX_VALUE;
rightArr[sizeOfRight + 1] = Integer.MAX_VALUE;

int i = 1;
int j = 1;

for(int k = begIndx; k < endIndx; k++) {
//use comparable here
if(leftArr[i] <= rightArr[j]) {
array[k] = leftArr[i];
i = i + 1;
}else {
///just replaces it so don't use comparable
array[k] = rightArr[j];
j = j + 1;
}
}
}
}

最佳答案

数组索引始终从零开始,因此如果您想访问数组中的第二个元素,则需要提供索引 1

如果您想按单个值扩展数组,您可以按如下方式创建一个临时数组:

public int[] expand(int[] arrayIn) {
int[] temp = new int[arrayIn.length + 1];
for (int i = 0; i < arrayIn.length; i++) {
temp[i] = arrayIn[i];
}
temp[arrayIn.length] = -1; // You can replace this with another "blank" value
}

因此,返回一个具有扩展索引读数的新数组(在本例中为-1

关于MergeSort算法中的Java IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203297/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com