Which type of sorting is used in the std::sort()?

后端 未结 7 1210
无人共我
无人共我 2020-12-01 09:34

Can anyone please tell me that which type of sorting technique (bubble, insertion, selection, quick, merge, count...) is implemented in the std::sort() function

相关标签:
7条回答
  • 2020-12-01 10:06

    Probably all implementations of std::sort use introsort (aka introspection sort), a hybrid algorithm that combines quicksort and heapsort. Actually, introsort was particularly invented in 1997 for the purpose of a performant sort implemenation in C++ STL.

    The only thing the standard requires is that std::sort somehow sort the data according to the specified ordering with a complexity of O(N log(N)); it is not guaranteed to be stable (there is a separate std::stable_sort algorithms available, if this should be required).

    Technically, introsort better meets the complexity requirement than quicksort: This is because heapsort has guaranteed O(N log(N)) complexity in the worst case, whereas quicksort has quadratic worst-case time.

    However, heapsort is 'slower' than quicksort in the average case, in the sense that heapsort performs C*N log(N) whereas quicksort has D*N log(n) performance, with D being significantly smaller than C (the numbers C and D are constants). In other words, the per-comparison-overhead of heapsort is higher than the one of quicksort.

    To get the best of both worlds, introsort starts with quicksort —a recursive algorithm—, but when recursion depth gets too high (which means it gets into a degenerated worst-case behaviour), it switches to heapsort.

    See also the Wikipedia entry for introsort or the original paper from David Musser, who invented introsort particularly for STL.

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