Is stdlib's qsort recursive?

前端 未结 9 1979
执念已碎
执念已碎 2020-12-30 09:19

I\'ve read that qsort is just a generic sort, with no promises about implementation. I don\'t know about how libraries vary from platform to plaform, but assumi

9条回答
  •  星月不相逢
    2020-12-30 10:11

    The worst-case space-complexity of a naive quicksort implementation (which is still a popular option for qsort) is O(N). If the implementation is modified to sort the smaller arary first and tail-recursion optimisation or an explicit stack and iteration is used then the worst case space can be brought down to O(log N), (what most answers here wrote already). So, you will not blow up your stack if the implementation of quick-sort is not broken and the library was not broken by improper compiler flags. But, for example, most compiler which support tail recursion elimination won't do this optimization it in unoptimized debug builds. A library built with the wrong flags (i.e. not enough optimization, for example in the embedded domain where you sometimes build your own debug libc) might crash the stack then.

    For most developers, this will never be an issue (they have vendor tested libc's which have O(log N) space complexity), but I'd say it is a good idea to have an eye on potential library issues from time to time.

    UPDATE: Here's an example for what I mean: A bug in libc (from 2000) where qsort would start thrashing virtual memory because the qsort implementation would switch internally to mergesort because it though there is enough memory to hold a temporary array.

    http://sources.redhat.com/ml/libc-alpha/2000-03/msg00139.html

提交回复
热议问题