简体   繁体   中英

Java IndexOutOfBoundsException in MergeSort algorithm

I keep getting

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at MergeSorter.merge(MergeSorter.java:44), MergeSorter.sort(MergeSorter.java:16), MergeSorter.sort(MergeSorter.java:14), MergeSorter.sort(MergeSorter.java:14), MergeSorter.sort(MergeSorter.java:14)

Not sure how to fix.

Also want to convert to generic afterwards.

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;
            }
        }       
    }   
}

Array indexes always start at zero, so if you wanted to access the second element in an array, you would provide the index 1 .

If you wanted to expand the array by a single value, you would create a temporary array as follows:

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
}

Thus, returning a new array with the extended index reading (in this case) -1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM