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)
count = array of k+1 zerosfor x in input docount[key(x)] += 1total = 0for i in 0, 1, ... k docount[i], total = total, count[i] + totaloutput = array of the same length as inputfor x in input dooutput[count[key(x)]] = xcount[key(x)] += 1return output
Name | Best | Average | Worst | Memory | Stable | Comments |
---|---|---|---|---|---|---|
Counting sort | n+k | n+k | n+k | 1 | Yes | n is the number of elements in input array and k is the range of input. |