Another solution, begins by building a max-heap with the first m elements of the given array, then scanning the remaining n − m elements and updating the heap as necessary, so that at any given moment the heap contains the m smallest elements seen so far. Finally, the heap is sorted. Its worst-case cost is Θ((m+n) log m) and it is not an interesting alternative unless m is quite small or we have to process the input
on-line.