What am I doing wrong in my quicksort implementation below:
public static void quicksort(int[] array, int start, int end) {
while (start < end) {
int pIndex = partition(array, start, end);
quicksort(array, start, pIndex - 1);
quicksort(array, pIndex + 1, end);
}
}
public static int partition(int[] array, int start, int end) {
int pivot = array[end];
int pIndex = start;
for (int i = start; i <= end - 1; i++) {
if (array[i] <= pivot) {
int tmp = array[pIndex]; // swap values
array[pIndex] = array[i];
array[i] = tmp;
pIndex++;
}
}
int tmpVal = array[pIndex];
array[pIndex] = pivot;
array[end] = tmpVal;
return pIndex;
}
When running this against the test case of an array {7, 5, 3, 6, 8, 1, 2, 4}, it rearranges the array into {1, 2, 3, 4, 8, 5, 7, 6} where it orders the left side of the array, but then enters what seems to be an infinite loop with the array of {1, 2} and never leaving that recursive call. I've tried adding a base case of if the array.length is less than 2, then return; but that makes no difference.
Here's a link to my code .
Anyone know what could be wrong?
Your loop
for (int i = 0; i <= end - 1; i++) {
Within partition
should be
for (int i = start; i <= end - 1; i++) {
With out this your pIndex can be outside of the range start
to end
and there for your recusive calls to quicksort will have the same parameters.
Another problem with your ideone code which is not shown above is
if (array.length < 2) { return; }
Within quicksort
you are not changing the length of your array so array.length
will always be 8.
A 3rd problem, and the one causing the infinite loop is
while (start < end) {
within quicksort
you are not changing the values for start or end during this loop, so this loop will never exit. see https://ideone.com/wY23C6 for a working example.
while (start < end) {
int pIndex = partition(array, start, end);
quicksort(array, start, pIndex - 1);
quicksort(array, pIndex + 1, end);
}
should be
if (start < end) {
int pIndex = partition(array, start, end);
quicksort(array, start, pIndex - 1);
quicksort(array, pIndex + 1, end);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.