为什么大多数人对元素少于n的子数组使用插入排序来优化快速排序? 我编写了一个插入排序函数和shell排序函数,并用几个具有10,50,100个元素的随机数组调用它们。似乎shell排序更快(我只用clock()测量时间;我不知道它是否是一个好方法)。如果它比插入排序更快,为什么没有更多人使用shell排序?插入排序功能有误吗?
我的代码:
double insertionSort(int *a, int size)
{
clock_t start, end;
int i, temp, pos;
start = clock();
for (i = 1; i < size; i++) {
temp = a[i];
pos = i - 1;
while (pos >= 0 && a[pos] > temp) {
a[pos + 1] = a[pos];
pos--;
}
a[pos + 1] = temp;
}
end = clock();
return (double)(end - start) / CLOCKS_PER_SEC * 1000;
}
double shellSort(int *a, int size)
{
int gaps[8] = {701, 301, 132, 57, 23, 10, 4, 1};
int i, k , temp, pos;
clock_t start, end;
start = clock();
for (i = 0; i < 8; i++)
for (k = gaps[i]; k < size; k++) {
temp = a[k];
pos = k - gaps[i];
while (pos >= 0 && a[pos] > temp) {
a[pos + gaps[i]] = a[pos];
pos -= gaps[i];
}
a[pos + gaps[i]] = temp;
}
end = clock();
return (double)(end - start) / CLOCKS_PER_SEC * 1000;
}
5的输出:
Insertion Sort : Sorted in 0.002000 milliseconds
Shell Sort : Sorted in 0.001000 milliseconds
10的输出:
Insertion Sort : Sorted in 0.004000 milliseconds
Shell Sort : Sorted in 0.001000 milliseconds
50的输出:
Insertion Sort : Sorted in 0.007000 milliseconds
Shell Sort : Sorted in 0.007000 milliseconds
100的输出:
Insertion Sort : Sorted in 0.015000 milliseconds
Shell Sort : Sorted in 0.014000 milliseconds
200的输出:
Insertion Sort : Sorted in 0.040000 milliseconds
Shell Sort : Sorted in 0.028000 milliseconds
答案 0 :(得分:0)