Counting Sort
✅ Counting Sort
non-comparison-based sorting algorithm counting: how many times does this element appear in input array?
- input array
get the biggest numbermax
- count array
size:max +1
output array
- get input array
- get the biggest number
max
- make count array with size of
max +1
- in count array, store count of unique element of input array at their respective indices
if 0 appears 2 times, input2
at index0
. - store cumulative sum in count array
- Update output array
outputArray[ countArray[ inputArray[i] ] – 1] = inputArray[i]
- also Update count array
countArray[ inputArray[i] ] = countArray[ inputArray[i] ]– -
⭐️ Keyword
✅ Code
✅ Time complexity
O(n+k)
n: size of input array
k: size of count array(range of input value)
✅ Space complexity
O(n+k)
n: size of output array
k: size of count array
👍🏻 Pros
- stable algorithm
- if range of input is of the order of number of input, faster (when k is smaller, faster)
👎🏻 Cons
- does not work for decimal value
- not in-place sorting algorithm
💡 Reference
This post is licensed under CC BY 4.0 by the author.