I'm learning datastructures and algorithms. So I have tried implementing the quick sort alogorithm.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 10, 16, 8, 12, 15, 6, 3, 9, 5 };
quickSort(0, arr.length - 1, arr);
}
public static void quickSort(int start, int end, int[] arr) {
if (start < end) {
int partitionIndex = partition(start, end, arr);
quickSort(start, partitionIndex - 1, arr);
quickSort(partitionIndex+1, end, arr); // When passing partitionIndex+1 in the swap method it throws index out of bound exception
System.out.println(Arrays.toString(arr));
}
}
public static int partition(int start, int end, int[] arr) {
int pivot = arr[end];
int pIndex = start;
for (int i = 0; i < end - 1; i++) {
if (arr[i] <= pivot) {
swap(i, pIndex, arr);
pIndex++;
}
}
swap(pIndex, end, arr);
return pIndex;
}
private static void swap(int i, int index, int[] arr) {
int temp = arr[i];
arr[i] = arr[index]; // index out of bound exception is thrown
arr[index] = temp;
}
When doing the recursive call quickSort(partitionIndex+1, end, arr);
and in the swap
method it is throwing index out of bound exception
. Because there is no such index to retrieve/store the value.
Can any one please help me to resolve this issue?