What sorting algorithm does qsort use?

后端 未结 3 1467
遇见更好的自我
遇见更好的自我 2021-01-17 21:48

I can\'t find any information regarding what sorting algorithm C qsort function uses.

Is it quicksort? It is not mentioned in man.

相关标签:
3条回答
  • 2021-01-17 22:22

    In theory, qsort is only defined to the point of the return values and call values of qsort and bsort. Here are ISO standard references.

    In practice, it usually uses quicksort.

    0 讨论(0)
  • 2021-01-17 22:45

    The implementation of qsort is not specified: an implementation may use any sorting algorithm. Interestingly, the sort does not need to be stable, and there is no complexity requirement.

    The entire specification of qsort (C11 §7.22.5.2) is as follows:

    The qsort function

    Synopsis

    #include <stdlib.h>
    void qsort(void *base, size_t nmemb, size_t size,
         int (*compar)(const void *, const void *));
    

    Description

    The qsort function sorts an array of nmemb objects, the initial element of which is pointed to by base. The size of each object is specified by size.

    The contents of the array are sorted into ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared. The function shall return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

    If two elements compare as equal, their order in the resulting sorted array is unspecified.

    Returns

    The qsort function returns no value.

    0 讨论(0)
  • 2021-01-17 22:45

    In complement to James McNellis’s quotation of the standard it is worth noting that GNU’s libc documentation says that

    The qsort function derives its name from the fact that it was originally implemented using the “quick sort” algorithm.

    and that it decided to use an alternative algorithm, apparently a merge sort.

    0 讨论(0)
提交回复
热议问题