0

I was practicing to do merge sort. This is the problem i got, it shows array index out of bounds, i checked the for loop and modified with < which was before <=, i dont know how to resolve

public class MergeSortProblem {
    
    public static void merge(int[] arr, int[] res, int low, int mid, int high) {
        
        int i = low, k= low, j=mid+1;
        
        while(i<=mid && j<=high) {
            
            if(arr[i] <= arr[j]) {
                res[k++] = arr[i++];
            }
            else {
                res[k++] = arr[j++];
            }
        }
        
        while(i<=mid) {
            res[k++] = arr[i++];
        }
        
        while(j<=high) {
            res[k++] = arr[j++];
        }
        
        for(i =low; i<=high; i++ ) {
            
            arr[i] = res[k];
            
        }
        
    }
    
    public static void divideArray(int[] arr, int[] res, int low, int high) {
        
        while(low == high) {
            return;
        }
        
        int mid = (low + high)/2 ;
        
        divideArray(arr, res, low,mid);
        divideArray(arr,res, mid+1, high);
        
        merge(arr,res,low,mid,high);
    }
    
    public static void main(String[] args) {
        
        int[] array = {6,10,5,7,6,8,3,80};
        
        int size = array.length;
        
        int start = 0;
        
        int[] result = {};
        
        divideArray(array,result,start,size);
    }
}

why am i getting array index out of bounds exception?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – OH GOD SPIDERS Aug 05 '21 at 14:57

1 Answers1

0
for(i =low; i<=high; i++ ) {             
     arr[i] = res[k];               
}

By looking at your code, this will return an array out of bounds exception. This happens because high is set to the arrays length 8 and you are looping from low to 8 because of the <= (the highest index of the array will be 7). It is always a good idea to use just < when looping through an array when using array.length

I recommend checking out Geeks For Geeks. They have a lot of examples of common algorythems like merge sort.