简体   繁体   中英

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

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; to force quicksort, call the undeclared _quicksort function and compile with gcc -static.

Regarding the compiller option I use CMake and I have set the cmake flags to:

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

but I am not sure how to call the undeclared _quicksort .

Does anyone have any experience with this?

Fix:

I have just declared the _quicksort function like @recycler suggested, in this manner:

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.

you could declare the function "_quicksort" in your c test code. This should be the same as qsort. Now you have to link it against the c-lib which should be done automatically by the linker. If the function _quicksort is exported, it can be used and the linker will link it to your binary. 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. 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. And mergesort was always about 25% faster than _quicksort. Which is probably why they replaced it. ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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