I have implemented a working quickSort algorithm using the first element in the array as the pivot, that look like this:
public int[] quickSort( int[] a, int st
You could simply swap the pivot you chose with the first element in the array before you start sorting, that way it'll work exactly as before.
int l = start;
int r = end;
this.swap(a, choosePivot(), start);
int pivotIndex = start;
If you choose to start with pivoting on an arbitrary element you have to change the behavior of your partitioning loop. See the code below:
/* Selecting the pivot to be a random-ish element
and pivotIndex to be beginning, since we don't know
where it will be until we loop through the list */
int pivot = a[someInt];
int pivotIndex = begin-1;
//have to keep track of where the pivot actually is in the list
int currentPivotIndex = someInt;
for(int i = begin; i <= end; i++) {
if(a[i] <= pivot) {
//for each element less than the pivot
//the pivotIndex moves by one
pivotIndex++;
//place the element to the left of the pivot
this.swap(a, pivotIndex, i);
//update currentPivotIndex if needed
if(a[pivotIndex] == pivot) {
currentPivotIndex = pivotIndex;
}
}
}
//put the pivot in its place
this.swap(a, pivotIndex, currentPivotIndex);
This is some odd behavior which is most probably caused by having your pivot element engage in partitioning.
The first line of the output says swapping l:8 and r:4
but it should have been swapping l:8 and r:3
. Because 4 is the pivot element and it doesn't belong to the partition on the left, nor to the partition on the right. It's the element in the middle of the partitions. It has to be isolated during partitioning.
To fix this issue, after you select your pivot, move it to the end. I.e, first thing, replace pivot with the last element of the array. Therefore, you can isolate it from the partitioning process. Then start the while loop with l = start and r = end - 1
because end
is currently pivot. Leave it alone. After you're done with partitioning, restore the pivot in the middle of the two partitions. The middle would be where l
and r
meet.
I believe following the above approach would fix your problem. Let me know if it doesn't.
Not directly related but your choice of the pivot element has a huge effect on the performance of quicksort. With its current version, hitting the worst-case (O(n^2)
) is likely. Most simply, you can choose it randomly, which brings O(nlogn)
complexity with high probability.