You have a list of n integers and you want the x smallest. For example,
x_smallest([1, 2, 5, 4, 3], 3)
should return [1, 2, 3]
.
I'll vote up unique runtimes within reason and will give the green check to the best runtime.
I'll start with O(n * x)
: Create an array of length x. Iterate through the list x times, each time pulling out the next smallest integer.
Edits
[1, 1, 1, 1, 1]
either.You can find the k-th smallest element in O(n) time. This has been discussed on StackOverflow before. There are relatively simple randomized algorithms, such as QuickSelect, that run in O(n) expected time and more complicated algorithms that run in O(n) worst-case time.
Given the k-th smallest element you can make one pass over the list to find all elements less than the k-th smallest and you are done. (I assume that the result array does not need to be sorted.)
Overall run-time is O(n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With