MergeSort算法中的Java IndexOutOfBoundsException
我一直在 线程“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) 不知道如何修复 之后还要转换为泛型MergeSort算法中的Java IndexOutOfBoundsException,java,sorting,indexoutofboundsexception,mergesort,Java,Sorting,Indexoutofboundsexception,Mergesort,我一直在 线程“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(MergeSo
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;
}
}
}
}
公共类合并分类器{
////稍后更改回通用
///数组是项
公共静态void排序(int[]数组,int begIndx,int endIndx){
if(数组==null){
抛出新的IllegalArgumentException(“项为null”);
}
if(begIndx for(int i=1;i数组索引总是从零开始,因此如果您想访问数组中的第二个元素,您可以提供索引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
}
public int[]展开(int[]数组){
int[]temp=新int[arrayIn.length+1];
for(int i=0;i
因此,使用扩展索引读取返回一个新数组(在本例中)-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
}
public int[]展开(int[]数组){
int[]temp=新int[arrayIn.length+1];
for(int i=0;i
因此,返回一个具有扩展索引读取的新数组(在本例中)-1