0
我想知道为什么我的quickSort太慢了。需要10-20秒对以下数组进行排序。 Bubblesort(如下所示)自动执行。为什么QuickSort比BubbleSort慢得多?
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 };
快速排序对于小数据集可能看起来较慢,因为您的quicksort实现包含递归调用。 – wns349 2013-02-16 13:00:40
bubblesort的最坏情况是n^2。 quicksort的wortcase复杂度是n * ln(n)。这是最糟糕的情况,它对个别情况没有任何规定。你的数据有多大,有多大? “自动”是什么意思? – 2013-02-16 13:06:01
对于我的代码中的数组,快速排序时间约为15秒,并且小于1秒。 – Stuart 2013-02-16 13:11:58