问题
Wrote this Java implementation of a recursive quicksort algorithm, and something seems to go awry as the array I am trying to sort almost sorts perfectly except for two elements that should be switched (near the middle of the array). The array of integers I am trying to sort is: 4, 77, 98, 30, 20, 50, 77, 22, 49, 2 (10 elements). Here is my code:
public static void quickSort(int[] array, int start, int end) {
if (start < end) {
int partition = partition(array, start, end);
quickSort(array, start, partition - 1);
quickSort(array, partition + 1, end);
}
}
public static int partition(int[] array, int left, int right) {
int pivotValue = array[(left + right) / 2]; //Value of middle element in array
while (left <= right) {
while (array[left] < pivotValue) {
left++;
}
while (array[right] > pivotValue) {
right++;
}
if (left <= right) {
/* swap code */
int temporary = array[left]
array[left] = array[right]
array[right] = temporary;
left++;
right--;
}
}
return left;
}
When I try this algorithm out with:
int[] array = {4, 77, 98, 30, 20, 50, 77, 22, 49, 2};
quickSort(array, 0, array.length - 1);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
It prints out: 2, 4, 20, 30, 22, 49, 50, 77, 77, 98
Any help figuring out why those two elements aren't correctly sorted would be highly appreciated. I'm sure it's something I missed while writing the partition code. Thanks!
回答1:
The problem is that you are leaving 1 element to be checked
just replace your code :
quickSort(array, start, partition - 1);
quickSort(array, partition + 1, end);
with this :
quickSort(array, start, partition - 1);
quickSort(array, partition, end);
or with this :
quickSort(array, start, partition);
quickSort(array, partition + 1, end);
I am assuming that the reason is clear now, but tell me if you need some explanation.
来源:https://stackoverflow.com/questions/26328296/partition-implementation-for-recursive-quicksort-in-java-is-not-working