SGI STL sort源码
temlate <class RandowAccessIterator>
inline void sort(RandowAccessIterator first, RandowAccessIterator last){
if(first ! = last){
_introsort_loop(first, last, value_type(first), _lg(last-first)*2);
_fina,_insertion_sort(first, last);
}
}
其中_lg()用来控制分割恶化的情况,分割的层数小于log2(last-first)*2,使用快排,大于时,使用堆排序
template <class RandowAccessIterator, class T, class size>
void _introsort_loop(RandowAccessIterator first, RandowAccessIterator last, T*,Size depth_limit){
//首先判断排序区间的元素个数,如果小于等于16,则直接使用插入排序,否则对区间分区
while((last - first) > _stl_threshold){
if(depth_limit == 0){//此时区间的分割次数达到了允许分割次数
partial_sort(first, last, last);//使用heapsort排序
return;
}
} --depth_limit; //以下是median-of-3 partition,选择一个够好的枢纽并决定分割点 //分割点将落在迭代器cut上
RandowAccessIterator cut = _unguarded_partition(first, last, T(_median(*first, *(first + (last - first)/2), *(last - 1)))); //对右半段递归进行sort _introsort_loop(cut, last, value_type(first), depth_limit); cut = last;
}
来源:https://www.cnblogs.com/zhousong918/p/10784964.html