-2

Getting ArrayIndexOutOfBoundsException at while (Arr1[i] <= pivot) i++; with test data 77 5 6 3 4 2

public int partition(int [] Arr1, int l, int h) {
    
    int pivot = Arr1[l];
    int i = l;
    int j = h;
    int temp;
    
    while (i < j) {
        while (Arr1[i] <= pivot) i++;
        while (Arr1[j] > pivot) j--;
        if(i<j) {
            temp = Arr1[i];
            Arr1[i] = Arr1[j];
            Arr1[j] = temp;
        }
    }
    
    if(i > j) {
        temp = Arr1[j];
        Arr1[j] = Arr1[l];
        Arr1[l] = temp;
    }
    
    return j;
    
    
}

1 Answers1

0

In the while you mentioned remove the equal sign, it’s not needed and it’s what causing the out of bounds. As you picked the highest number to be the pivot, it will be true for every number in your array with the equal sign.

SgtOmer
  • 200
  • 1
  • 1
  • 8