- template <class RandomAccessIterator>
- inline void partial_sort(RandomAccessIterator first,
- RandomAccessIterator middle,
- RandomAccessIterator last) {
- __partial_sort(first, middle, last, value_type(first));
- }
- template <class RandomAccessIterator, class T>
- void __partial_sort(RandomAccessIterator first,
- RandomAccessIterator middle,
- RandomAccessIterator last, T*) {
- make_heap(first, middle);
- for(RandomAccessIterator i = middle; i != last; ++i)
- if(*i < *first)
- __pop_heap(first, middle, i);
- sort_heap(first, middle);
- }
从上述代码可以看出,partial_sort()函数借用heap进行部分排序。partial_sort()还有另外一版本,即partial_sort_copy(first1, last1, first2, last2),该函数的原理于partial_sort()相同,不过是将[first1, last1)中最小的(last2 - first2)个元素拷贝到[first2, last2)中。