I’m trying to implement several different types of quicksort in java, but none of my implementations seem to be working. I’ve looked all over the internet and my code looks very similar to all the code that i’ve found, so I have no idea whats wrong. My code is as follows: (Note that this isn’t complete but I figure if I find whats wrong with one quicksort, the other versions will work as well) Edit: The problem i’m having is that the array doesn’t sort correctly. I run a simple method called isSorted to tell me whether the array was sorted correctly. It works with other sorting methods (insertion sort, heap sort etc.) but reports false when used with my implementation of quicksort
public static void quickSort(int[] A) {
flag=0;
quickSortHelper(A, 0, A.length-1);
}
public static void quickSortHelper(int [] A, int low, int high){
if(low<high){
if(flag==0){
int q=DPartition(A, low,high,A[high]);
quickSortHelper(A,low,q-1);
quickSortHelper(A,q+1,high);
}
public static int DPartition(int [] A, int low, int high,int pivot){
int p=pivot;
int i=low;
int j=high-1;
while (i<=j){
while(i<=j && A[i]<=p){
i=i+1;
}
while(j>=i && A[j]>=p){
j=j-1;
}
if (i<j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
int temp = A[i];
A[i] = A[p];
A[p] = temp;
return i;
}
The bug is in your
DPartitionmethod. In quick sort, you move in a particular direction, and as soon as swapping is performed, you change the direction you move. But, in the above code, you are moving in both the direction without swapping.The first inner-while loop finds the location of swap, but instead of swapping, you started with the next inner-while, which starts moving in opposite direction. That is faulty.
You should maintain one more variable to store the direction in the array.
You can try modifying your code like this (Not Tested): –