arrayssortingmergesortarrayindexoutofboundsexception

Where is the problem in code for which I am facing Array Index out of Bounds problem?


I am facing a problem in Merge Sort coded in Java language. Please can you see where I am wrong because I am facing Index out of bounds problem. I am sharing the code. Please check !

The error in the output box is :

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1"

Code : code

import java.util.Arrays;

public class Sorting {

    public static void main(String[] args) {
        int[] arr = {5,3,4,7,2,8,6,9,1};
        mergesort(arr);
    }


static void mergesort(int[] arr){

        mergesortalgorithm(arr,0, arr.length);
        System.out.println("The sorted array is :" + Arrays.toString(arr));
    }
    static void mergesortalgorithm(int[] arr,int lb,int ub){
        if (lb < ub){
            int mid = (lb + ub)/2;
            mergesortalgorithm(arr,lb,mid);
            mergesortalgorithm(arr,mid + 1,ub);
            merge(arr,lb,mid,ub);
        }
    }
    static void merge(int[] arr,int lb,int mid,int ub){
        int i = lb;
        int j = mid + 1;
        int k = 0;
        int[] newarray = new int[lb + ub];
        while (i <= mid && j <= ub){
            if (arr[i] <= arr[j]){
                newarray[k] = arr[i];
                i++;
            }
            else {
                newarray[k] = arr[j];
                j++;
            }
            k++;
        }
        if (i > mid){
            while (j <= ub){
                newarray[k] = arr[j];
                j++;
                k++;
            }
        }
        else {
            while (i <= mid){
                newarray[k] = arr[i];
                i++;
                k++;
            }
        }
        for (int l = lb;l <= ub;l++){
            arr[l] = newarray[l];
        }
    }
}

Solution

  • ArrayIndexOutOfBoundsException is an exception thrown when you try to reach an item of an array using an invalid index that is outside its bounds.

    An array of an elements has its first element indexed as 0, the second as 1 and so on, the last index being n - 1.

    So, let's say you have an array of int[] arr = {5,3,4,7,2,8,6,9,1}, which is of 9 elements. This means that trying to reach an element having a negative index (such as arr[-4]) or trying to reach any items of it beyond 8 (such as arr[9] or arr[234]) will throw an `ArrayIndexOutOfBoundsException.

    A very simple way to get past such errors is to find the exact line where it is occurring, like

    newarray[k] = arr[i];
    

    and seeing that when k becomes 1, then newarray, which has a single element cannot reference it, as it has a single element, having an index of 0. So, in order to get past this issue one is tempted to add safety checks that ensure that you never get past the boundaries, such as

    while ((i <= mid && j <= ub) && (i < arr.length) && (j < arr.length)){
    

    eventually reaching to the syntactically correct

    static void merge(int[] arr,int lb,int mid,int ub){
        int i = lb;
        int j = mid + 1;
        int k = 0;
        int[] newarray = new int[lb + ub];
        while ((i <= mid && j <= ub) && (i < arr.length) && (j < arr.length)){
            if (arr[i] <= arr[j]){
                newarray[k] = arr[i];
                i++;
            }
            else {
                newarray[k] = arr[j];
                j++;
            }
            k++;
        }
        if (i > mid){
            while ((j <= ub) && (k < newarray.length) && (j < arr.length)){
                newarray[k] = arr[j];
                j++;
                k++;
            }
        }
        else {
            while ((i <= mid) && (k < newarray.length)){
                newarray[k] = arr[i];
                i++;
                k++;
            }
        }
        for (int l = lb;(l <= ub) && (l < newarray.length) && (l < arr.length);l++){
            arr[l] = newarray[l];
        }
    }
    

    , but this only copes with the syntactical issues and does not scratch the logical problem that you have and will yield the incorrect [0, 0, 0, 0, 0, 0, 3, 3, 0] as the result. So, clearly, your problem does not consist in getting the index out of bounds exception, it's only the symptom. The actual problem is in the logic.

    So, you have some assumption that's faulty. But what it could be? For starters, you have this line:

    mergesortalgorithm(arr,0, arr.length);
    

    Think about this line: the first item is the 0'th, while the last item is the arr.length'th item. How many items do you have here? A total of arr.length + 1 items. This means that you will definitely get out of bounds when you refer the last item. So, you need to fix your logic and at the end you will most probably not even need for syntactic safety checks if your algorithm is guaranteed to work inside the proper bounds. The line above should be changed to

    mergesortalgorithm(arr,0, arr.length - 1);
    

    Also, you will need to keep track of how your indexes are changed, especially k and how exactly you implemented the algorithm.