java - Quicksort:wikipedia-implementation 不工作

标签 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. 您需要从分区中选择枢轴值,而不仅仅是取数组的第一个元素

  2. 最后一次交换应该在循环之外,您是在遍历分区后将枢轴元素放到它所在的位置。看最后两行:

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 
}

关于java - Quicksort:wikipedia-implementation 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30061709/

相关文章:

mysql - 类似excel的SQL多排序数据库

java - Android比较特殊字母

java - 我可以访问不在 Struts 2 ValueStack 上的另一个操作的属性吗?

java - 如何使用具有正常 "Given"语句的示例表(Parametrised Scenarios)

Python 图像教程有效,其他图像表现不同(使用 Pylab 显示图像)

ios - ALAssetsLibrary 在位置获取照片

algorithm - 查找单词所有形式的最佳方法是什么?

r - 首先根据 r 中的一列对 dataframe 进行排序,然后根据另一列进行排序

java - 在 TreeMap 中搜索 (Java)

java - 搞砸了 CSV 导致异常