我在C visual studio中运行了带有排序数组(升序)和未排序数组(降序)的选择排序算法。结果是,未排序的数组的性能要比大尺寸的排序数组的性能要快。
我认为这很荒谬。选择排序是否总是需要恒定的时间取决于数组大小?为什么是这样??
这是selectionsort。我用n = 100,000到1,000,000来运行它。每次运行我将其增加100,000。
int main() {
int array[1000000]; //1,000,000
int i = 100000; //100,000
int n = 100000; //100,000
for (int k = 0; k < 10; ++k) {
insert_ascending(array, n); //stuff elements in ascending order
//time check
sort(array, n);
insert_decending(array, n); //stuff elements in descending order
//time check
sort(array, n);
n += i;
}
}
void selectionSort(int *list, const int n)
{
int i, j, indexMin, temp;
for (i = 0; i < n - 1; i++)
{
indexMin = i;
for (j = i + 1; j < n; j++)
{
if (list[j] < list[indexMin])
{
indexMin = j;
}
}
temp = list[indexMin];
list[indexMin] = list[i];
list[i] = temp;
}
}
这是我的0.02€。
我可以看到在GCC上未优化的代码中,有4%的速度差异有利于降序数组而不是升序数组。我的假设是它是由
if (list[j] < list[indexMin]) {
indexMin = j;
}
被编译为
...
jge .L4
mov eax, DWORD PTR [rbp-8]
mov DWORD PTR [rbp-12], eax
.L4:
add DWORD PTR [rbp-8], 1
也就是说,这不是分支预测失败-对于上升情况,jge
始终分支,对于下降情况,它永不分支。jge
与实际更新缓存中的索引变量相比,采用分支确实需要更多的周期。
当然,如果在启用优化的情况下进行编译,则升序代码将获胜。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句