-1

I'm getting the following error: Index 7 out of bounds for length 4 at line 10 and 34. I would appreciate if somone could explain this to me as well as if I am even recursively calling the function correclty. Bear in mind I understand there are hundreds of examples of this function online, I just wanted to see if I could do it myself.

package pckg;

public class MergeShift {
    
    private static int[] testArr = {5,3,6,8,2,1,7,4};
    
    public static void main(String[] args) 
    {
        
        int[] sortedArr = mergeShift(testArr);
        
        for(int i=0; i<sortedArr.length;i++) 
        {
            System.out.print(sortedArr[i] + "\t");
            System.out.println();
            
        }
    }
    
    public static int[] mergeShift(int[] arr) 
    {
        
    
        int[] left = new int[arr.length/2];
        int[] right = new int[arr.length/2];
        
        for(int i=0;i<arr.length/2;i++) 
        {
            left[i] =arr[i];
        }
        
        for(int j=arr.length-1;j>=arr.length/2;j--) 
        {
            right[j] = arr[j];
            
        }
        
        if(left.length>1) 
        {
            mergeShift(left);
            
        }
        
        if(right.length>1)
        
        {
            mergeShift(right);
            
        }
        
        else 
        {
            int[] finalArr = mergeArr(left,right);
            return finalArr;
        }

        return right;
        
    }
    
    public static int[] mergeArr(int[] left, int[] right) 
    {
        
        int[] mergedArr = new int[left.length + right.length];
        
        for(int i=0; i<mergedArr.length/2;i++) 
        {
            mergedArr[i] = left[i];
            
        }
        
        for(int j=mergedArr.length-1;j>=mergedArr.length/2;j--) 
        {
            mergedArr[j] = right[j];
            
        }
        
        return mergedArr;
        
    }
    

}
Progman
  • 16,827
  • 6
  • 33
  • 48

1 Answers1

0

j has a length of 7 in line 32. But right has only a length of 4 (line 25 because of arr.length/2).

In line 34 it tries to reach right[7] and thus it is right[4] out of bound.

Jens
  • 17
  • 1
  • 4