Partition Implementation for Recursive Quicksort in Java is not working

被刻印的时光 ゝ 提交于 2019-12-06 13:57:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!