STL source code profiling algorithm stl_algo.h -- partial_sort/partial_sort_copy

Source: Internet
Author: User

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.
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.