GCC 9.2.0 libstdc++ 源码确认 introsort
其他 have mentioned introsort,但这里有一些 libstc++ 的证据,它是大多数 Linux 发行版上的默认 C++ 实现。
libstdc++ 是 GCC 本身的一部分,因此我们将研究 GCC 源代码。
libstdc++-v3/include/std/algorithm 是主标题,包含:
#include <bits/stl_algobase.h>
#include <bits/stl_algo.h>
然后,bits/stl_algo.h 包含排序重载的定义,其中之一是:
/**
* @brief Sort the elements of a sequence.
* @ingroup sorting_algorithms
* @param __first An iterator.
* @param __last Another iterator.
* @return Nothing.
*
* Sorts the elements in the range @p [__first,__last) in ascending order,
* such that for each iterator @e i in the range @p [__first,__last-1),
* *(i+1)<*i is false.
*
* The relative ordering of equivalent elements is not preserved, use
* @p stable_sort() if this is needed.
*/
template<typename _RandomAccessIterator>
inline void
sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
{
// concept requirements
__glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
_RandomAccessIterator>)
__glibcxx_function_requires(_LessThanComparableConcept<
typename iterator_traits<_RandomAccessIterator>::value_type>)
__glibcxx_requires_valid_range(__first, __last);
__glibcxx_requires_irreflexive(__first, __last);
std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
}
所以我们看到这只是对输入进行了一系列健全性检查,然后调用std::__sort,即defined in the same file:
template<typename _RandomAccessIterator, typename _Compare>
inline void
__sort(_RandomAccessIterator __first, _RandomAccessIterator __last,
_Compare __comp)
{
if (__first != __last)
{
std::__introsort_loop(__first, __last,
std::__lg(__last - __first) * 2,
__comp);
std::__final_insertion_sort(__first, __last, __comp);
}
}
我会在这里停下来,我们已经达到了一个名为 std::__introsort_loop 的标识符,其余的实现都在同一个文件上,如果有人仍然有疑问的话。
在std::set 中提到的std::set 中提到的What is the underlying data structure of a STL set in C++?
C++17 并行排序
我们现在也有并行排序,所以也值得看看它是如何完成的:Are C++17 Parallel Algorithms implemented already?
如上面回答中提到的,实现依赖于一个外部库:Intel Thread Building Blocks:https://github.com/intel/tbb