- 论坛徽章:
- 0
|
我抄来的c++快速排序方法(stl_algo.h):
- template<typename _RandomAccessIter>
- inline void
- sort(_RandomAccessIter __first, _RandomAccessIter __last)
- {
- typedef typename iterator_traits<_RandomAccessIter>::value_type _ValueType;
- // concept requirements
- __glibcpp_function_requires(_Mutable_RandomAccessIteratorConcept<
- _RandomAccessIter>)
- __glibcpp_function_requires(_LessThanComparableConcept<_ValueType>)
- if (__first != __last) {
- __introsort_loop(__first, __last, __lg(__last - __first) * 2);
- __final_insertion_sort(__first, __last);
- }
- }
- template<typename _RandomAccessIter, typename _Size>
- void
- __introsort_loop(_RandomAccessIter __first, _RandomAccessIter __last,
- _Size __depth_limit)
- {
- typedef typename iterator_traits<_RandomAccessIter>::value_type _ValueType;
- while (__last - __first > _M_threshold) {
- if (__depth_limit == 0) {
- partial_sort(__first, __last, __last);
- return;
- }
- --__depth_limit;
- _RandomAccessIter __cut =
- __unguarded_partition(__first, __last,
- _ValueType(__median(*__first,
- *(__first + (__last - __first)/2),
- *(__last - 1))));
- __introsort_loop(__cut, __last, __depth_limit);
- __last = __cut;
- }
- }
- template<typename _RandomAccessIter>
- void
- __final_insertion_sort(_RandomAccessIter __first, _RandomAccessIter __last)
- {
- if (__last - __first > _M_threshold) {
- __insertion_sort(__first, __first + _M_threshold);
- __unguarded_insertion_sort(__first + _M_threshold, __last);
- }
- else
- __insertion_sort(__first, __last);
- }
- template<typename _RandomAccessIter>
- void
- partial_sort(_RandomAccessIter __first,
- _RandomAccessIter __middle,
- _RandomAccessIter __last)
- {
- typedef typename iterator_traits<_RandomAccessIter>::value_type _ValueType;
- // concept requirements
- __glibcpp_function_requires(_Mutable_RandomAccessIteratorConcept<
- _RandomAccessIter>)
- __glibcpp_function_requires(_LessThanComparableConcept<_ValueType>)
- make_heap(__first, __middle);
- for (_RandomAccessIter __i = __middle; __i < __last; ++__i)
- if (*__i < *__first)
- __pop_heap(__first, __middle, __i, _ValueType(*__i));
- sort_heap(__first, __middle);
- }
- template<typename _RandomAccessIter, typename _Tp>
- _RandomAccessIter
- __unguarded_partition(_RandomAccessIter __first, _RandomAccessIter __last,
- _Tp __pivot)
- {
- while (true) {
- while (*__first < __pivot)
- ++__first;
- --__last;
- while (__pivot < *__last)
- --__last;
- if (!(__first < __last))
- return __first;
- iter_swap(__first, __last);
- ++__first;
- }
- }
复制代码
[ 本帖最后由 lgfang 于 2008-10-27 15:30 编辑 ] |
|