Given an integer array, effectively sort it using the count sort algorithm.

We have already discussed the counting sort algorithm in detail, which can be used to sort non-negative integers between a specific range. This post covers a variation of counting sort that can work on negative numbers and can sort numbers in any range. But this version doesn’t produce a stable sort, i.e., the relative order of items with equal keys is not preserved anymore and runs in O(n.log(n)) time, where n is the total number of elements in the input collection.

 
The idea remains the same – iterate over the collection and construct a map storing information about the total number of times each key occurs within the input collection. Then loop over the collection again and then use those counts to determine each key value’s final positions in the collection. This takes advantage of the fact that a map is sorted according to the keys’ natural order (ascending order).

Following is the C++, Java, and Python implementation of count sort that takes O(n) space:

C++


Download  Run Code

Output:

1 1 1 2 2 4 4 4 10

Java


Download  Run Code

Output:

[1, 1, 1, 2, 2, 4, 4, 4, 10]

Python


Download  Run Code

Output:

[1, 1, 1, 2, 2, 4, 4, 4, 10]