Edit page

Counting Sort

In computer science, counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently. (Source: Wikipedia)

Pseudocode

count = array of k+1 zeros
for x in input do
count[key(x)] += 1
total = 0
for i in 0, 1, ... k do
count[i], total = total, count[i] + total
output = array of the same length as input
for x in input do
output[count[key(x)]] = x
count[key(x)] += 1
return output

Complexity

NameBestAverageWorstMemoryStableComments
Counting sortn+kn+kn+k1Yesn is the number of elements in input array and k is the range of input.

References

  • Geeksforgeeks
  • Wikipedia
  • YouTube
  • Programiz
  • Hackerearth
  • Tutorialspoint