[英]Quick sort runtime speed concerns
I am having something that troubles me. 我有麻烦的事。 I have my implementation of a quick sort algorithm, but when I test it on an array of integers that has over 30 elements, sorting takes, in my opinion to long.
我已经实现了快速排序算法,但是当我在具有30多个元素的整数数组上对其进行测试时,我认为排序需要很长时间。 Sometimes even more than 10 seconds, unlike with selection sort, insertion sort and bubble sort, which are faster on 10000 elements than quick sort on 100 elements.
有时甚至超过10秒,这与选择排序,插入排序和冒泡排序不同,后者在10000个元素上比在100个元素上进行快速排序更快。
Here is my solution, please give advice :) 这是我的解决方案,请提出建议:)
void kvikSort(int a[], int l, int d) {
int i, k;
if (l >= d)
return;
k = l;
swap(&a[l], &a[(l + d) / 2]);
for (i = l + 1; i <= d; i++)
if (a[i] < a[l])
swap(&a[++k], &a[i]);
swap(&a[l], &a[k]);
kvikSort(a, 0, k-1);
kvikSort(a, k+1, d);
}
EDIT: I am using GCC v 4.7.2 on my Linux Mint 14, proc: intel core2duo e7400 编辑:我在Linux Mint 14上使用GCC v 4.7.2,过程:intel core2duo e7400
EDIT: My other algorithms: 编辑:我的其他算法:
void selectionSort(int a[], int n) {
int i, j, min;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
if (min != i)
swap(&a[min], &a[i]);
}
}
void insertionSort(int a[], int n) {
int i, j;
for (i = 0; i < n - 1; i++)
for (j = i + 1; j > 0 && a[j] < a[j-1]; j--)
swap(&a[j], &a[j-1]);
}
void bubbleSort(int a[], int n) {
int i, j;
for (i = n - 1; i > 0; i--)
for (j = 0; j < i; j++)
if (a[j] > a[j+1])
swap(&a[j], &a[j+1]);
}
void swap(int *i, int *j) {
int tmp;
tmp = *i;
*i = *j;
*j = tmp;
}
EDIT: Maybe I should mention that in my test program I am first outputing randomly generated array to a text file, then sorted array to another text file. 编辑:也许我应该提到,在我的测试程序中,我首先将随机生成的数组输出到文本文件,然后将数组排序到另一个文本文件。 So it is certainly running slow, but that's not the problem, the problem is that quick sort runs a lot slower than the rest.
因此,它的运行速度肯定很慢,但这不是问题,问题在于快速排序的运行速度比其他排序要慢得多。
Your first recursive call 您的第一个递归调用
kvikSort(a, 0, k-1);
has the wrong lower bound, it should be 下限有误,应该是
kvikSort(a, l, k-1);
With a lower bound of 0, you re-sort the initial part of the array again and again. 下限为0,您一次又一次地重新排列数组的初始部分。
Here's the problem: 这是问题所在:
void kvikSort(int a[], int l, int d) {
int i, k;
if (l >= d)
return;
k = l;
swap(&a[l], &a[(l + d) / 2]);
for (i = l + 1; i <= d; i++)
if (a[i] < a[l])
swap(&a[++k], &a[i]);
swap(&a[l], &a[k]);
>>> kvikSort(a, 0, k-1);
kvikSort(a, l, k-1);
kvikSort(a, k+1, d);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.