首页 > 其他 > 详细

STL--sort源码分析

时间:2019-04-28 17:09:08      阅读:144      评论:0      收藏:0      [点我收藏+]

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;
  
}

 

STL--sort源码分析

原文:https://www.cnblogs.com/zhousong918/p/10784964.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!