Search code examples
c++sortingqsortstable-sort

What is the difference between inbuilt qsort function and stable sort function?


From various sources cited I know that in-built C function, stable_sort is stable but qsort is unstable. If that is the case why do we use qsort at all? Isn't it redundant? Why not use stable_sort instead?


Solution

  • The reason to choose quick sort over stable sort is mostly speed: qsort is often faster than stable_sort, which should come as no surprise, because stable_sort comes with a stronger guarantee.

    O(N·log2(N)). If additional memory is available, then the complexity is O(N·log(N)).

    Space is another consideration: qsort is done in place, meaning that no additional memory allocation is required. stable_sort, on the other hand, tries a temporary allocation of the size equal to the array being sorted.

    This function attempts to allocate a temporary buffer equal in size to the sequence to be sorted. If the allocation fails, the less efficient algorithm is chosen.

    Note from rcgldr's comment: (The HP / Microsoft implementation of std::stable_sort uses a temporary buffer 1/2 the size of the sequence. The second half is sorted into the second half of the sequence, the first half into the temporary buffer, then the temporary buffer and second half of the sequence are merged back into the sequence.