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.