I've encountered some issue with one of my do-while loops while trying to implement quickSort, scpecifically in partitioning method. This particular loop is causing problems since the index is getting out of bounds and honestly I don't know why:
do {
j--;
} while (array[j] > pivot);
and full code:
public static void main(String[] args) {
int tab[] = {-5, 12, 6, -2, 7, 9, 1};
quickSort(tab, 0, tab.length-1);
for (int x: tab){
System.out.print(x+" ");
}
}
public static int partition(int array[], int left, int right){
int pivot = array[left];
int i = left;
int j = right;
while (i < j) {
do {
i++;
} while (array[i] <= pivot);
do {
j--;
} while (array[j] > pivot);
if (i < j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int temp = pivot;
pivot = array[j];
array[j] = pivot;
return j;
}
public static void quickSort(int array[], int left, int right){
if (left < right) {
int pivot = partition(array, left, right);
quickSort(array, left, pivot);
quickSort(array, pivot + 1, right);
}
}
Kind regards,