STL源碼解析 - sort

 

 模板函數sort有兩個重載版本

template<class _RanIt> inline
	void sort(_RanIt _First, _RanIt _Last);


 

template<class _RanIt,
	class _Pr> inline
	void sort(_RanIt _First, _RanIt _Last, _Pr _Pred);


第一個版本使用小於操作符(operator<),第二個版本使用自定義的二元謂詞(binary predicate)

其功能是實現一個區間內的元素的不穩定快速排序,下面針對源代碼進行註釋說明,以第一個版本爲例

template<class _RanIt> inline
	void sort(_RanIt _First, _RanIt _Last)
	{	// order [_First, _Last), using operator<
	_DEBUG_RANGE(_First, _Last);
	std::_Sort(_CHECKED_BASE(_First), _CHECKED_BASE(_Last), _Last - _First);
	}

 

_Sort 函數,_ISORT_MAX == 32

template<class _RanIt,
	class _Diff> inline
	void _Sort(_RanIt _First, _RanIt _Last, _Diff _Ideal)
	{	// order [_First, _Last), using operator<
	_Diff _Count;
	for (; _ISORT_MAX < (_Count = _Last - _First) && 0 < _Ideal; )
		{	// divide and conquer by quicksort
		// 快速排序實現分治法
		// 近似分區
		pair<_RanIt, _RanIt> _Mid =
			std::_Unguarded_partition(_First, _Last);
		// 防止分區過多,逗號表達式
		_Ideal /= 2, _Ideal += _Ideal / 2;	// allow 1.5 log2(N) divisions

		if (_Mid.first - _First < _Last - _Mid.second)
			{	// loop on second half
			// 左區間遞歸排序
			std::_Sort(_First, _Mid.first, _Ideal);
			// 更新整體區間起點
			_First = _Mid.second;
			}
		else
			{	// loop on first half
			// 右區間遞歸排序
			std::_Sort(_Mid.second, _Last, _Ideal);
			// 更新整體區間終點
			_Last = _Mid.first;
			}
		}

	// _Ideal == 0
	if (_ISORT_MAX < _Count)
		{	// heap sort if too many divisions
		// 分區達到最大值時採用堆排序
		std::make_heap(_First, _Last);
		std::sort_heap(_First, _Last);
		}
	else if (1 < _Count)	// 元素較少時採用插入排序
		std::_Insertion_sort(_First, _Last);	// small
	}


_Unguarded_partition和_Insertion_sort1 見文章《STL - nth_element》

make_heap見文章《STL - make_heap》

sort_heap見文章《STL - sort_heap》

 

代碼來自於Microsoft Visual Studio 2008 SP1 安裝包的algorithm文件,版本歸原作者所有!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章