STL sort

 

   1: template<class _RanIt> inline
   2:     void sort(_RanIt _First, _RanIt _Last)
   3: {    // order [_First, _Last), using operator<
   4:     _DEBUG_RANGE(_First, _Last);
   5:     _Sort(_CHECKED_BASE(_First), _CHECKED_BASE(_Last), _Last - _First);
   6: }
   1: template<class _RanIt,
   2:     class _Diff,
   3:     class _Pr> inline
   4:     void _Sort(_RanIt _First, _RanIt _Last, _Diff _Ideal, _Pr _Pred)
   5:     {    
   6:     // order [_First, _Last), using _Pred
   7:     _Diff _Count;
   8:     for (; _ISORT_MAX < (_Count = _Last - _First) && 0 < _Ideal; )
   9:     {    
  10:         // divide and conquer by quicksort
  11:  
  12:         // First, we get the middle position, divide the set to two part
  13:         pair<_RanIt, _RanIt> _Mid =
  14:             _Unguarded_partition(_First, _Last, _Pred);
  15:  
  16:         
  17:         _Ideal /= 2, _Ideal += _Ideal / 2;    // allow 1.5 log2(N) divisions
  18:  
  19:         if (_Mid.first - _First < _Last - _Mid.second)    // loop on larger half
  20:             _Sort(_First, _Mid.first, _Ideal, _Pred), _First = _Mid.second;
  21:         else
  22:             _Sort(_Mid.second, _Last, _Ideal, _Pred), _Last = _Mid.first;
  23:     }
  24:  
  25:     if (_ISORT_MAX < _Count)
  26:     {    
  27:         // heap sort if too many divisions
  28:         std::make_heap(_First, _Last, _Pred);
  29:         std::sort_heap(_First, _Last, _Pred);
  30:     }
  31:     else if (1 < _Count)
  32:         _Insertion_sort(_First, _Last, _Pred);    // small, insertion sort
  33:     }

其中

   1: // COMMON SORT PARAMETERS
   2: const int _ISORT_MAX = 32;    // maximum size for insertion sort

 

1. _ISORT_MAX用来控制能够conquer的集合的大小,如果集合已经足够小了,比如这里集合中元素的个数小于32个,则可以使用Insertion_Sort来进行排序操作了;

2. _Ideal用来控制(Divide-and-Conquer)递归的层次,

相当 (N * 1.5_Ideal) >> (_Ideal) 次就达到了0,即2_Ideal == N*1.5_Ideal,

即_Ideal = log4/3N, 但是实际上由于在“除2”操作过程中的低位损耗,_Ideal的值会比公式计算出来的偏小,不过原comment给出的1.5 log2(N)是不准确的,以下做了一些对比

   1: int x = 1024;
   2:     int y = 0;
   3:     while (x > 0)
   4:     {
   5:         x /= 2, x += x / 2;
   6:         printf("0x%08X\n", x);
   7:         y++;
   8:     }
N1.5 log2(N)log4/3N程序计算出的值y
1024152421

 

言归正传,当_Ideal的层次太深的时候,for循环结束

3. 如果不是因为分块已经足够小了而结束的,就调用Heap_Sort进行堆排序

4. 如果分块已经都足够小了,就进行Insertion_Sort排序

转载于:https://www.cnblogs.com/long123king/p/3487753.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值