I am trying to implement a quickSort by taking last Element as the pivot. But I am unable to produce a valid output.
Also what change needs to be done in order to make it randomized? I am coding in Java.
public class QuickSortDemo {
public static void quicksort(int A[], int temp[], int left, int right) {
int q, i;
//why u need to check this base case always
if (left < right) {
q = partition(A, temp, left, right);
quicksort(A, temp, left, q - 1);
quicksort(A, temp, q + 1, right);
for (i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
}
public static int partition(int A[], int temp[], int left, int right) {
int x, i, j;
x = A[right];
i = left - 1;
for (j = left; j <= right - 1; j++) {
if (A[j] <= x) {
i = i + 1;
A[i] = A[j];
}
}
A[i + 1] = A[right];
return i + 1;
}
public static void main(String s[]) {
int ar[] = {6, 3, 2, 5, 4};
int p[] = new int[ar.length];
quicksort(ar, p, 0, ar.length - 1);
}
} //end class QuickSortDemo
OutputShown
2
2
4
5
4
2
2
4
4
4
2
2
4
4
4