Counting Sort
Last updated
Last updated
Counting sort is a sorting algorithm that sorts the elements of an array by counting the number of occurrences of each unique element in the array. The count is stored in an auxiliary array and the sorting is done by mapping the count as an index of the auxiliary array.
Find out the maximum element (let it be max
) from the given array.Given array
Initialize an array of length max+1
with all elements 0. This array is used for storing the count of the elements in the array.Count array
Store the count of each element at their respective index in count
array
For example: if the count of element 3 is 2 then, 2 is stored in the 3rd position of count array. If element "5" is not present in the array, then 0 is stored in 5th position.Count of each element stored
Store cumulative sum of the elements of the count array. It helps in placing the elements into the correct index of the sorted array.Cumulative count
Find the index of each element of the original array in the count array. This gives the cumulative count. Place the element at the index calculated as shown in figure below.Counting sort
After placing each element at its correct position, decrease its count by one.
Given an integer array with many duplicated elements, write an algorithm to efficiently sort it in linear time, where the order of equal elements doesnโt matter.
For example,
Input: { 4, 2, 40, 10, 10, 1, 4, 2, 1, 10, 40 }
A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n.log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array.
A better approach is to use a counting sort. This will bring down the time complexity to O(n + k), where n
is the size of the input and k
is the input range.
Output: { 1, 1, 2, 2, 4, 4, 10, 10, 10, 40, 40 }