【发布时间】: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