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
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.