Home > Software design >  Index 16 out of bounds for length 16
Index 16 out of bounds for length 16

Time:02-28

I am trying to sort an array of x elements using quickSort but I am getting an error "Index 16 out of bounds for length 16" please help.

public class quickSort {
    static int partition(int []arr, int lo, int hi){
        int pivot=arr[lo];
        while(lo<hi){
            while(pivot<arr[hi] && lo<hi)
                hi = hi - 1;
                if (hi != lo) {
                    arr[lo] = arr[hi];
                    lo = lo   1;
                }
            while(arr[lo]<pivot && lo<hi)
                lo =lo 1;
                if(hi!=lo){
                    arr[hi]=arr[lo];
                    hi =hi-1;
                }
        }
        arr[hi] =pivot;
        int pivotPoint = partition(arr,lo,hi);
        return pivotPoint;
    }
    static void quickSort(int[] arr, int lo, int hi){
        int pivotPoint =partition(arr,lo,hi);
        if(lo<pivotPoint){
            quickSort(arr,lo,pivotPoint-1);
        }
        if(lo<pivotPoint){
            quickSort(arr,pivotPoint 1,hi);
        }
    }
    static void Sort(int[] arr, int n){
        quickSort(arr,1,n);
    }
    public static void main(String[] args) {
        int[] random ={16,9,8,10,11,12,13,14,15,16,2,3,6,7,4,5};
        Sort(random,random.length);
        System.out.println();
    }
}

CodePudding user response:

For an array of 16 elements the indexes are 0 to 15. Thus index 16 is not part of the array and you get the OutOfBoundsException.

  • Related