You can use the selection algorithm to find the k-th lowest element, and then repeat and return it and all the elements below. More work needs to be done if the list may contain duplicates (make sure that you do not get more items that you need).
This solution is O(n) . The selection algorithm is implemented in C ++ as nth_element()
Another option is to use max heap of size k , and also repeat these elements, while maintaining a bunch of all k smallest elements.
for each element x: if (heap.size() < k): heap.add(x) else if x < heap.max(): heap.pop() heap.add(x)
When you are done, the heap contains k smallest elements.
This is O(nlogk)
source share