Counting sort

Counting sort is not based on comparisons like most other sorting methods are, and its time complexity is thus not bounded by O(nlogn) as all comparison sorts are. This method of sorting is used when all elements to be sorted fall in a known, finite and reasonably small range.

For example, we might need to sort a billion numbers which all lie between 1 and 1000. In this case, the best comparison sort would take O(nlogn) time, which is rather slow. However, we can create an array with 1000 elements. As we read in each number, we increment its corresponding array element by 1. When all inputs have been read in, we iterate through the 1000 elements in the array and we can print the numbers in order.

int i; int buckets[1000] = {0}; /* must initialize to all 0 */

while (scanf("%d", &i) != EOF) buckets[i - 1]++;