Counting Sort is a unique sorting algorithm that is not comparison-based. Instead of comparing elements, it works by counting the number of objects that have each distinct key value. It is only effective when the range of potential items in the input list is not significantly greater than the number of items.
It is an integer sorting algorithm, meaning it's used for sorting integers.
max).max + 1 and initialize all its elements to 0. This array will store the count of each unique element.3 three times, count[3] will be 3.Here is a function that implements the counting sort algorithm.
def counting_sort(data):
n = len(data)
// The output array that will have sorted data
output = [0] * n
// Find the maximum element in the input array
max_val = max(data)
// Create a count array to store count of individual elements
// and initialize count array as 0
count = [0] * (max_val + 1)
// Store count of each character
for i in range(n):
count[data[i]] += 1
// Change count[i] so that count[i] now contains actual
// position of this element in output array
for i in range(1, max_val + 1):
count[i] += count[i - 1]
// Build the output character array
i = n - 1
while i >= 0:
output[count[data[i]] - 1] = data[i]
count[data[i]] -= 1
i -= 1
// Copy the output array to data, so that data now
// contains sorted characters
for i in range(n):
data[i] = output[i]
// --- Usage ---
my_list = [4, 2, 2, 8, 3, 3, 1]
counting_sort(my_list)
print("Sorted list is:", my_list)
Let n be the number of elements and k be the range of the input (max_val).
k is not significantly larger than n.Limitations: Counting sort is highly efficient but not versatile. It's not suitable for data with a very large range of values (e.g., sorting a few 64-bit integers) because it would require an enormous count array. It's also not typically used for non-integer data like floats or strings.