Implement counting sort
Standard · Write code · about 15 min
Sort nums in ascending order with counting sort. Every value is an integer from 0 to k.
Count each key, turn the counts into running totals, then place the values from right to left into a new array. Return that array.
Example 1
Input:
[[2,5,3,0,2,3,0,3],5]
Output:
[0,0,2,2,3,3,3,5]
Example 2
Input:
[[],0]
Output:
[]
An empty array is already sorted.
Constraints
- 0 ≤ nums.length ≤ 1,000
- 0 ≤ nums[i] ≤ k ≤ 100
- Return a new sorted array; do not use a library sort
Learn the idea first: Counting sort, a visual lesson.
More Counting sort problems
- Fill the count array Warm-up
- Count each key Warm-up
- Fill in the stable placement Standard
- Spot the bug: equal keys swap order Standard
- Sort by a bounded key, stably Challenge