在Java中,快速排序方式比插入和选择排序慢?
所以我在复习我的算法知识并测试不同种类的运行时,我发现我的快速排序实现比插入和选择排序慢得多。该算法在我看来是正确的,在实践中它与我在网上找到的其他几个实现看起来是相同的。但它一定是错的,因为它比O(N^2)排序慢500倍。对随机10000个元素数组的3个(深度)副本进行排序的计时给出: 插入排序:(75355000纳秒) 选择排序:(287367000纳秒) 快速分拣:(44609075000纳秒) 代码如下:在Java中,快速排序方式比插入和选择排序慢?,java,performance,algorithm,sorting,quicksort,Java,Performance,Algorithm,Sorting,Quicksort,所以我在复习我的算法知识并测试不同种类的运行时,我发现我的快速排序实现比插入和选择排序慢得多。该算法在我看来是正确的,在实践中它与我在网上找到的其他几个实现看起来是相同的。但它一定是错的,因为它比O(N^2)排序慢500倍。对随机10000个元素数组的3个(深度)副本进行排序的计时给出: 插入排序:(75355000纳秒) 选择排序:(287367000纳秒) 快速分拣:(44609075000纳秒) 代码如下: public static void quickSort(Thing [] the
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);
}
}
公共静态void快速排序(Thing[]things,int left,int right){
int i=左;int j=右;
int pivot=things[(int)(左+(右左)*0.5)].getValue();
而(我)
j--;
如果(i)
快速排序(Things,i,right);
}
}
Thing类只是我在算法中使用的一个虚拟对象。它在构造函数中有一个由Random生成的整数值,其他的就不多了
我已经验证了快速排序是否正确地对数组进行排序—只是比它应该的速度慢得多。我尝试过不同的轴心选择方法。我已经尝试了我能想到的一切。也许我太近了,看不到它,但有人能告诉我是什么扼杀了我的算法吗?你应该在
while
循环完成后递归快速排序数组的每个部分,而不是每次都通过while
循环。这完全正确。耶稣,谢谢你,先生!我离得太近了,看不见它。新运行时为(9411000 ns)