C++之STL中sort函式的內部實現(二)
阿新 • • 發佈:2019-01-03
另外一個版本:
概述
先進行introsort,基本有序後再使用insertion sort。introsort是改進的quick sort,為了防止最壞情況發生,它使用__lg()函式控制分割惡化的情況。
intro sort演算法
- 元素個數檢查,大於16個才進行後續操作;
- 分割層次檢查,分割層次超過指定值就使用heap sort;
- 全部檢查通過後使用quick sort,使用median-of-3方法確定樞軸位置;
- 對左右半段遞迴進行intro sort。
- 全部內容結束後, 序列已經基本有序,再次呼叫一次insertion sort。
程式碼
inline void sort (RAIterator first, RAIterator last){
if(first != last){
__introsort_loop(first,last,value_type(first),__lg(last-first)*2);
__final_insertion_sort(first,last);//採用insertion sort
}
}
//控制分割惡化,找出滿足2^k <= n時,k的最大值。
inline size __lg(size n){
size k;
for(k = 0; n > 1; n>>=1 ) ++k;
return k;
}
void __introsort_loop(RAIterator first,RAIterator last,T*,size depth_limit){
while(last - first > __stl_threshold){//全域性常數__stl_threshold = 16
if(depth_limit == 0){
partial_sort(first,last,last);//分割惡化後改用heap sort
return;
}
--depth_limit;
//http ://blog.csdn.net/u010902721/article/details/45868391
//上面這個連結裡有介紹,__median是選三值的中值作為樞軸。下面這個函式是quick sort
RAIterator cut = __unguarded_partition(first,last,__median(*first,*(first+(last-first)/2),*(last-1)));
//遞迴右半段
__introsort_loop(cut,last,value_type(first),depth_limit);
last = cut;//回到while迴圈,對左半段再次進行sort
}
}