I have written code of Quick Sort but it is showing Exception Array Index Out of bound.This works properly when written in C but in Java it is not working.Please tell what is the problem with it.Any Suggestion is appreciated.It is two way partition standard CLRS algorithm.
package Sorting;
public class QuickSort {
public static void main(String arg[]) {
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
Sort(a, 0, a.length - 1);
for (int i = 0; i < 9; i++) {
System.out.print(" " + a[i]);
}
}
private static void Sort(int[] a, int i, int j) {
// TODO Auto-generated method stub
if (i < j) {
int k = Partition(a, i, j);
Sort(a, i, k - 1);
Sort(a, k + 1, j);
}
}
private static int Partition(int[] a, int i, int j) {
// TODO Auto-generated method stub
int temp;
int x = a[j];
int l = i - 1;
for (int n = i; n < j; n++) {
if (a[n] >= x) {
l++;
temp = a[l];
a[l] = a[n];
a[n] = temp;
}
}
temp = a[x];
a[x] = a[l + 1];
a[l + 1] = temp;
return l + 1;
}
}
Output: 9 3 5 7 4 1 6 2 8
Partitioncan't work. See theforloop. The condition isi < j. Neitherinorjchanges in the body. Once execution enters, it's the Hotel California: "You can check out any time you like, but you can never leave."System.err.print), to figure out whyPartitionis not working. You will never learn if we debug your program for you.