mercredi 22 juin 2016

MergeSort - ArraysOutOfBoundsException

Was studying sorting algorithms via a free online course where the instructor was using the main() method to show how to print the results.

Decided to use a JUnit test instead a main method.

However, I am getting the following StackTrace:

java.lang.ArrayIndexOutOfBoundsException: 8
    at MergeSort.sort(MergeSort.java:30)
    at MergeSort.sort(MergeSort.java:14)
    at MergeSort.sort(MergeSort.java:14)
    at MergeSortTest.sort(MergeSortTest.java:14)

MergeSort.java (actual implementation):

import java.util.Arrays;

public class MergeSort {

    public static String sort(int[] array, int[] tmpArray, int lowIndex, int highIndex) {
        int midIndex =0;
        int lowIndex1 = 0;
        int lowIndex2 = 0;
        int i = 0;

        // Divide up sets using recursion
        if (highIndex > lowIndex) {
            midIndex = (highIndex + lowIndex) / 2;
            sort(array, tmpArray, lowIndex, midIndex);
            sort(array, tmpArray, midIndex + 1, highIndex);
        }

        lowIndex1 = lowIndex;
        lowIndex2 = midIndex+1;

        System.arraycopy(array, 0, tmpArray, 0, array.length);

        // Merge elements
        while(lowIndex <= midIndex && lowIndex2 <= highIndex) {
            if (tmpArray[lowIndex1] <= tmpArray[lowIndex2]) {
                array[i] = tmpArray[lowIndex1];
                lowIndex1++;
            }
            else {
                array[i] = tmpArray[lowIndex2];
            }
            i++;
        }
        while (lowIndex1 <= midIndex) {
            array[i] = tmpArray[lowIndex1];
            i++;
            lowIndex1++;
        }
        while (lowIndex2 <= highIndex) {
            array[i] = tmpArray[lowIndex2];
            i++;
            lowIndex2++;
        }
        return Arrays.toString(array);
    }
}

MergeSortTest.java:

import java.util.Arrays;

import org.junit.Test;

public class MergeSortTest {

    int[] array = new int[] {6, 4, 10, 9, 3, 7, 2, 1};
    int[] sortedArray = new int[] {1, 2, 3, 4, 6, 7, 9, 10};
    int[] tmp = new int[array.length];

    @Test
    public void sort() {
        System.out.println("Unsorted array: " + Arrays.toString(array));
        String value = MergeSort.sort(array, tmp, 0, array.length - 1);
        assert(value == Arrays.toString(sortedArray));
        System.out.println("Sorted array: " + value);
    }
}

What am I possibly doing wrong?

Aucun commentaire:

Enregistrer un commentaire