【问题标题】:Quicksort WAY slower than Insertion and Selection Sort in Java?快速排序方式比 Java 中的插入和选择排序慢?
【发布时间】:2014-05-17 10:27:46
【问题描述】:

所以我正在复习我的算法知识和测试不同种类的运行时,我发现我的快速排序实现比插入和选择排序要慢得多。该算法在我看来是正确的,在实践中它看起来与我在网上找到的其他几个实现相同。但它一定是错误的,因为它比 O(N^2) 排序慢 500 倍。对随机的 10000 个元素数组的 3 个(深)副本进行排序给出:

插入排序:(75355000 ns)

选择排序:(287367000 ns)

快速排序:(44609075000 ns)

代码如下:

public static void quickSort(Thing [] theThings, int left, int right) {
    int i= left; int j = right;
    int pivot = theThings[(int)(left + (right-left)*0.5)].getValue();

    while (i <= j) {
        while (theThings[i].getValue() < pivot)
            i++;
        while (theThings[j].getValue() > pivot)
            j--;

        if (i <= j) {
            Thing temp = theThings[i];
            theThings[i] = theThings[j];
            theThings[j] = temp;

            i++;
            j--;
        }

        if (left < j)
            quickSort(theThings, left, j);
        if (right > i)  
            quickSort(theThings, i, right);
    }                   
}

Thing 类只是我在算法中用来玩的一个假人。它有一个由 Random 在构造函数中生成的整数值,仅此而已。

我已经验证了快速排序确实正确地对数组进行了排序 - 只是比它应该慢得多。我尝试了不同的枢轴选择方法。我已经尝试了我能想到的一切。也许我离得太近了,但谁能告诉我是什么杀死了我的算法?

【问题讨论】:

    标签: java performance algorithm sorting quicksort


    【解决方案1】:

    您应该在while 循环完成后递归对数组的每个部分进行快速排序,而不是每次都通过while 循环。

    【讨论】:

    • 这完全正确。耶稣,谢谢你,先生!我离得太近了,看不到它。新的运行时间是 (9411000 ns)
    猜你喜欢
    • 2021-03-11
    • 2021-06-06
    • 2010-10-04
    • 2016-02-18
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多