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:     }
N 1.5 log2(N) log4/3N 程序计算出的值y
1024 15 24 21

 

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

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

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

posted @ 2013-12-23 17:06  Daniel King  阅读(227)  评论(0编辑  收藏  举报