【发布时间】:2013-02-01 08:35:33
【问题描述】:
我想知道为什么我的 quickSort 这么慢。对以下数组进行排序需要 10-20 秒。冒泡排序(如下所示)会自动完成。
public static void quickSort(int[] tab, int lowIndex, int highIndex) {
if (tab == null || tab.length == 0) {
return;
}
int i = lowIndex;
int j = highIndex;
int pivot = tab[lowIndex + (highIndex - lowIndex) / 2];
while (i <= j) {
while (tab[i] < pivot) {
i++;
}
while (tab[j] > pivot) {
j--;
}
if (i <= j) {
int c = tab[i];
tab[i] = tab[j];
tab[j] = c;
i++;
j--;
}
if (lowIndex < j) {
quickSort(tab, lowIndex, j);
}
if (i < highIndex) {
quickSort(tab, i, highIndex);
}
}
}
public static void bubbleSort(int[] arr) {
int n = arr.length - 1;
while (n >= 1) {
for (int i = 0; i < n; i++) {
if (arr[i] > arr[i + 1]) {
int c = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = c;
}
}
n--;
}
}
public static void main(String[] args) {
int[] t = new int[] { 5, 1, 33, 13, 21, 2, 12, 4,
2, 3, 53, 2, 125, 23, 53, 523, 5, 235, 235, 235, 23, 523, 1,
2, 41, 2412, 412, 4, 124, 1, 241, 24, 1, 43, 6, 346, 457, 56,
74, 5, 3, 5, 1, 33, 13, 21, 2, 12, 4,
2, 3, 53, 2, 125, 23, 53, 523, 5, 235, 235, 235, 23, 523, 1,
2, 41, 2412, 412, 4, 124, 1, 241, 24, 1, 43, 6, 346, 457, 56,
74, 5, 3, 74, 5, 3, 5, 1, 33, 13, 21, 2, 12, 4,
2, 3, 53, 2, 125, 23, 53, 523, 5, 235, 235, 235, 23, 523, 1,
2, 41, 2412, 412, 4, 124, 1, 241, 24, 1, 43, 6, 346, 457, 56,
74, 5, 3 };
【问题讨论】:
-
对于小型数据集,快速排序可能看起来较慢,因为您的快速排序实现包含递归调用。
-
冒泡排序的最坏情况复杂度是 n^2。快速排序的工作情况复杂度为 n*ln(n)。这些是最坏的情况,它没有说明个别情况。你的数据有多随机,有多大? “自动”是什么意思?
-
对于我的代码中的数组,快速排序时间约为 15 秒,而冒泡排序不到 1 秒。
-
@bmorris591 代码示例似乎包含一些示例数据。
-
您的
quicksort似乎不正确。递归调用不应出现在while (i <= j)循环内。除此之外可能还有其他问题 - 你应该真正看看标准实现,通过谷歌存在数百万,例如:mycstutorials.com/articles/sorting/quicksort
标签: java algorithm quicksort bubble-sort