Search code examples
algorithmsortingcounting-sort

Why is counting sort not used for large inputs?


Counting sort is the sorting algorithm with a average time complexity of O(n+K), and the counting sort assumes that each of the input element is an integer in the range of 0 to K.

Why can't we linear-search the maximum value in an unsorted array, equal it to K, and hence apply counting sort on it?


Solution

  • In the case where your inputs are arrays with maximum - minimum = O(n log n) (i.e. the range of values is reasonably restricted), this actually makes sense. If this is not the case, a standard comparison-based sort algorithm or even an integer sorting algorithm like radix sort is asymptotically better.

    To give you an example, the following algorithm generates a family of inputs on which counting sort has runtime complexity Θ(n^2):

    def generate_input(n):
        array = []
        for i := 1 to n:
            array.append(i*i);
        shuffle(array)
        return array