An algorithm for finding the smallest number of n in M

Source: Internet
Author: User

This question is a common problem, my approach is to use the heap.

The implementation of Partial_sort algorithm in intercepting STL:

template <class RandomAccessIterator, class T, class Compare>
void __partial_sort(RandomAccessIterator first, RandomAccessIterator middle,
  RandomAccessIterator last, T*, Compare comp) {
  make_heap(first, middle, comp);
  for (RandomAccessIterator i = middle; i < last; ++i)
    if (comp(*i, *first))
      __pop_heap(first, middle, i, T(*i), comp, distance_type(first));
  sort_heap(first, middle, comp);
}

The above function is a partial ordering of a sequence, sorted by order of elements between first,middle.

Its approach is to first generate a heap of data from the original First,middle, and then iterate over the data, and if the largest element in the previous element is larger, delete the smallest element into the new element, the process is LG (MIDDLE-FIRST), and finally heap sort.

Not every element needs to resize the heap, so the worst case time complexity is n * LG (MIDDLE-FIRST).

Similarly, this algorithm can be used to solve this problem by using a heap algorithm, as stated above, the worst time complexity is n * LG (M), where n is the total element, and M is the largest number of m to be searched.

Based on the idea above, and the heap algorithm I used to write, give the code to solve this problem, because my original heap algorithm is a large heap (max-heap), that is, the largest element of the heap in the root, so this is to find out the number of the smallest 10 number, if the maximum number of 10, To say that the heap changed to a small heap, in fact, is to change the size of the relationship between the father and son in the heap, the rest of the place unchanged.

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.