The k smallest values
Standard · Write code · about 10 min
Return the k smallest values of nums in ascending order. Use only k passes of selection sort instead of sorting the whole array.
Example 1
Input:
[[29,10,14,37,13],2]
Output:
[10,13]
Example 2
Input:
[[5,1,4],3]
Output:
[1,4,5]
k = n returns the whole array sorted.
Constraints
- 0 ≤ k ≤ nums.length ≤ 1,000
- -1,000 ≤ nums[i] ≤ 1,000
Learn the idea first: Selection sort, a visual lesson.
More Selection sort problems
- State after two passes Warm-up
- Count comparisons Warm-up
- Is selection sort stable? Standard
- Implement selection sort Standard
- Selection sort of pairs by key Challenge