STL source code profiling algorithm stl_algo.h -- partial_sort/partial_sort_copy
Certificate -----------------------------------------------------------------------------------------------------------------------------------------
Description: This algorithm accepts a middle iterator (in the column of the sequence [first, last) and reschedules [first, last ),
Sort the middle-first smallest elements in the sequence in ascending order and place them in [first, last.
The remaining last-middle elements are placed in [middle, last), and there is no guarantee that there is any specific order.
Ideas:
Heap sort is used inside the algorithm.
1. Use make_heap () to organize [first, middle) into a max-heap
2. Compare each element in [middle, last) with the heap top element of max-heap. If it is smaller than this value, the position is swapped and the max-heap state is retained.
3. Now [first, middle) stores a smaller middle-first element, and then uses sort_heap () to sort [first, middle ].
Complexity: Time klog (n )?
Figure: 6-11
Source code:
template
inline void partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last) { __partial_sort(first, middle, last, value_type(first));}template
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, T(*i), distance_type(first)); sort_heap(first, middle);}
Example:
int A[] = {7, 2, 6, 11, 9, 3, 12, 10, 8, 4, 1, 5};const int N = sizeof(A) / sizeof(int);partial_sort(A, A + 5, A + N);copy(A, A + N, ostream_iterator
(cout, ));// The printed result is 1 2 3 4 5 11 12 10 9 8 7 6.