简体   繁体   English

强制 C 库 qsort 执行快速排序而不是合并排序

[英]Force C library qsort to perform a quicksort rather than a mergesort

I am rather new to C and I am reading this post: Killing Quicksort我是 C 的新手,我正在阅读这篇文章: Killing Quicksort

and it says:它说:

A note of caution for those playing along at home: the GNU C library qsort function is actually mergesort if the C library thinks the computer has enough free memory;对于那些在家玩的人要注意:如果 C 库认为计算机有足够的空闲 memory,则 GNU C 库 qsort function 实际上是归并排序; to force quicksort, call the undeclared _quicksort function and compile with gcc -static.要强制快速排序,请调用未声明的 _quicksort function 并使用 gcc -static 进行编译。

Regarding the compiller option I use CMake and I have set the cmake flags to:关于编译器选项,我使用 CMake 并将 cmake 标志设置为:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99 -static")

but I am not sure how to call the undeclared _quicksort .但我不确定如何调用未声明的_quicksort

Does anyone have any experience with this?有人对这个有经验么?

Fix:使固定:

I have just declared the _quicksort function like @recycler suggested, in this manner:我刚刚像@recycler 建议的那样以这种方式声明了 _quicksort function:

void _quicksort(void *__base, size_t __nmemb, size_t __size,
        __compar_fn_t __compar);

and it seems to behave like a quicksort now.它现在看起来像一个快速排序。 I am a beginner in C, and for me this seems like magic, but anyway, I consider myself satisfied for now.我是 C 的初学者,对我来说这似乎很神奇,但无论如何,我认为自己现在很满意。

you could declare the function "_quicksort" in your c test code.您可以在 c 测试代码中声明函数“_quicksort”。 This should be the same as qsort.这应该与 qsort 相同。 Now you have to link it against the c-lib which should be done automatically by the linker.现在您必须将它与应该由链接器自动完成的 c-lib 链接。 If the function _quicksort is exported, it can be used and the linker will link it to your binary.如果函数 _quicksort 已导出,则可以使用它,并且链接器会将其链接到您的二进制文件。 If it is not exported you get an error.如果未导出,则会出现错误。

This is the quick and dirty option.这是快速而肮脏的选择。 You could also read the sources of the GNU C lib.您还可以阅读 GNU C 库的源代码。 Maybe there is another option.也许还有另一种选择。

Just a heads up - your mileage may vary, but I just tested the glibc versions of _quicksort and mergesort at all different sizes and with arrays that were randomized, in order, and in anti-order.请注意 - 你的里程可能会有所不同,但我只是测试了 glibc 版本的 _quicksort 和 mergesort 在所有不同的大小和 arrays 随机,顺序和反顺序。 And mergesort was always about 25% faster than _quicksort. mergesort 总是比 _quicksort 快 25%。 Which is probably why they replaced it.这可能就是他们更换它的原因。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM