Quicksort:维基百科 - 实现无法解决

时间:2015-05-05 19:33:20

标签: java algorithm sorting quicksort

我只是尝试从维基百科(https://en.wikipedia.org/wiki/Quicksort)实现快速排序算法,但缺少某些东西。这是我的代码:

public static void quicksort(int[] a, int lo, int hi) {
    if(lo < hi) {
        int p = partition(a, lo, hi);
        quicksort(a, lo, p - 1);
        quicksort(a, p + 1, hi);
    }
}

public static int partition(int[] a, int lo, int hi) {
    //choose pivot element
    int pivotIndex = 0; 
    int pivotVal = a[pivotIndex];

    //put pivot at the end of array
    swap(a, pivotIndex, hi);

    //compare other elements to pivot and swap accordingly
    int storeindex = lo;
    for(int i = lo; i < hi; i++) {
        if(a[i] <= pivotVal) {
            swap(a, i, storeindex);
            storeindex++;
        }
        //set pivot in right place of array
        swap(a, storeindex, hi);
    }

    return storeindex; //return 
}

public static void swap(int[] a, int place1, int place2) {
    int temp = a[place1];
    a[place1] = a[place2];
    a[place2] = temp;
}

这是一个出错的例子:

 int[] a = {1,2,3,4,5};
 quicksort(a, 0, a.length - 1);

返回:1, 2, 3, 5, 4 而不是它应该:      1, 2, 3, 4, 5

我已经盯着这一段很长一段时间了,如果有人能帮助我找出错误的地方,我将不胜感激:)谢谢!

1 个答案:

答案 0 :(得分:4)

两个问题:

  1. 您需要从分区中选择枢轴值,而不只是选择数组的第一个元素

  2. 最后一次交换应该在循环之外,你在遍历分区后将pivot元素放在它的位置。见最后两行:

  3. enter image description here

    固定分区方法:

    public static int partition(int[] a, int lo, int hi) {
        //choose pivot element
        int pivotIndex = lo; // ERROR 1 fixed
        int pivotVal = a[pivotIndex];
    
        //put pivot at the end of array
        swap(a, pivotIndex, hi);
    
        //compare other elements to pivot and swap accordingly
        int storeindex = lo;
        for (int i = lo; i < hi; i++) {
            if (a[i] <= pivotVal) {
                swap(a, i, storeindex);
                storeindex++;
            }
        }
    
        //set pivot in right place of array
        swap(a, storeindex, hi); // ERROR 2 fixed
        return storeindex; //return 
    }