STL--sort源码分析

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值