Counting
Counting Sort is an efficient, non-comparison-based sorting algorithm suitable for sorting integers when the range of the elements to be sorted is known beforehand.
It works by counting the number of occurrences of each unique element in the input array and then using these counts to place each element in its correct sorted position.
pseudocode:
In this example:
countingSort
function takes an arrayarr
as input and returns a sorted array.It first finds the maximum value in the input array to determine the range of values.
It creates an array
counts
to store the count of occurrences of each element.It counts the occurrences of each element in the input array.
It modifies the
counts
array to store the position of each element in the sorted array.It creates a sorted array
sortedArr
using the counts array.
The time complexity of Counting Sort is O(n + k), where n is the number of elements in the input array and k is the range of the input.
However, it requires extra space proportional to the range of the input array.
Last updated