Does the Linux implementation of quicksort “back off” to insertion sort?

旧城冷巷雨未停 提交于 2019-12-11 01:57:56

问题


I was reading in Bentley & McIlroy (1993) that their suggested implementation of Quicksort uses Insertion Sort when the arrays get small enough.

I was curious to know whether modern-day kernels use this same maneuver. Does anyone know whether the Linux kernel, for instance, switches from Quicksort to Insertion Sort in this way?


回答1:


Assuming you mean the qsort from the C library, here's the qsort() from a somewhat recent glibc, which is the one used in most Linux systems: http://www.cs.umaine.edu/~chaw/200801/capstone/n/qsort.c.html.

It does indeed switch to insertion for small partitions. It happens to use 4 elements for the threshold, though it's possible the empirically-selected number needs updating.

/* Discontinue quicksort algorithm when partition gets below this size.
   This particular magic number was chosen to work best on a Sun 4/260. */
#define MAX_THRESH 4



回答2:


If you're referring to the qsort from the Linux standard C library (GLIBC), that's actually implemented as merge sort, not quick sort. It will only fall back to an in-place quick sort if it's unable to allocate enough memory for merge sort.

Don't believe me? Check out the source code for qsort() in GLIBC here: http://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/msort.c;hb=HEAD#l306

Mats Linander has a great article summarizing the various implementations for qsort() in different standard C libraries here: http://calmerthanyouare.org/2013/05/31/qsort-shootout.html (hint: most don't actually use quick sort!)



来源:https://stackoverflow.com/questions/19123683/does-the-linux-implementation-of-quicksort-back-off-to-insertion-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!