My Quicksort seems to stop before completely sorting the array, and I've stared myself blind on the code.
I wrote the algorithm according to the related chapters in Java Software Structures - Designing and Using Data Structures (3rd Edition)
Quick Sort:
private static <T extends Comparable<T>> void quickSort(T[] array,int min, int max){
int pIndex;
if (max-min > 0) {
pIndex = partition(array, min, max);
quickSort(array, min, pIndex-1);
quickSort(array, pIndex+1, max);
}
}
Partition:
private static <T extends Comparable<T>> int partition(T[] array, int min, int max) {
int left, right;
T pivot, temp;
int middle = (min+max)/2;
left = min;
right = max;
pivot = array[middle];
while (left < right) {
while (array[left].compareTo(pivot) <= 0 && left < right)
left++;
while (array[right].compareTo(pivot) > 0)
right--;
if (left<right) {
temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
temp = array[min];
array[min] = array[right];
array[right] = temp;
return right;
}
The input:
An int[10] array containing the values 0 through 9, shuffled.
The quicksort-function is thus called like: quicksort(nums, 0, nums.length-1)
The output (example):
0
2
1
3
7
4
5
6
8
9
As you can see, the end product seems to be somewhat on the way to a good end-product, but it's stopping prematurely somewhere.
Update:
None of the answers provided so far (the deleted ones included) worked. If nobody is able to spot the bug, would anyone kindly redirect me to a good source for generic algorithms in Java?
I even shamefully attempted to do a pure copypaste of the Quicksort algorithm from the book mentioned above, and while it compiled and ran, it resulted in the same, "almost-correct" output as above. I then questioned whether or not it may be my input data, but nope. It is simply an Integer-array of integers, no duplicates. It's a valid candidate to my understanding.