In this tutorial, you will learn how **count sort** works. Additionally, you will discover working instances of counting sort in C, C++, Java, and Python.

Contents

## What is a counting sort algorithm?

**Counting sort** is perhaps the most well-known sorting algorithm – it plays out some arithmetic calculations in order to get the perfect output sequence.

## Algorithm

- Calculate the range of an array for example maximum and least elements.
- Create an array of that range.
- Calculate the frequency of every element in the given array and store it in the recently created array.
- Change the frequency array such that it contains the sum of frequencies of the past one.
- The changed array will contain the situation of every entry.

Counting sort is a sorting algorithm that sorts the elements of an array by counting the number of events of every unique element in the array. The count is put away in an auxiliary array and the sorting is finished by planning the count and index of the auxiliary array.

## How Counting Sort Works?

- Discover the maximum element (let it be max) from the given array.

2. Instate an array of length max+1 with all elements 0. This array is used for putting away the count of the elements in the array.

3. Store the count of every element at their particular index in count array

For instance: on the off chance that the count of element 3 is 2, 2 is put away in the third situation of count array. On the off chance that element “5” is absent in the array, 0 is put away in the fifth position.

4. Store the cumulative sum of the elements of the count array. It helps in setting the elements into the correct index of the sorted array.

5. Discover the index of every element of the first array in the count array. This gives the cumulative count. Spot the element at the index calculated as demonstrated in the figure underneath.

6. Subsequent to putting every element at its correct position, decrease its count by one.

## Counting Sort Algorithm

countingSort(array, size) max <- find largest element in array initialize count array with all zeros for j <- 0 to size find the total count of each unique element and store the count at jth index in count array for i <- 1 to max find the cumulative sum and store it in count array itself for j <- size down to 1 restore the elements to array decrease count of each element restored by 1

## Python, Java, and C/C++ Examples

**Python**

# Counting sort in Python programming def countingSort(array): size = len(array) output = [0] * size # Initialize count array count = [0] * 10 # Store the count of each elements in count array for i in range(0, size): count[array[i]] += 1 # Store the cummulative count for i in range(1, 10): count[i] += count[i - 1] # Find the index of each element of the original array in count array # place the elements in output array i = size - 1 while i >= 0: output[count[array[i]] - 1] = array[i] count[array[i]] -= 1 i -= 1 # Copy the sorted elements into original array for i in range(0, size): array[i] = output[i] data = [4, 2, 2, 8, 3, 3, 1] countingSort(data) print("Sorted Array in Ascending Order: ") print(data)

**Java**

// Counting sort in Java programming import java.util.Arrays; class CountingSort { void countSort(int array[], int size) { int[] output = new int[size + 1]; // Find the largest element of the array int max = array[0]; for (int i = 1; i < size; i++) { if (array[i] > max) max = array[i]; } int[] count = new int[max + 1]; // Initialize count array with all zeros. for (int i = 0; i < max; ++i) { count[i] = 0; } // Store the count of each element for (int i = 0; i < size; i++) { count[array[i]]++; } // Store the cummulative count of each array for (int i = 1; i <= max; i++) { count[i] += count[i - 1]; } // Find the index of each element of the original array in count array, and // place the elements in output array for (int i = size - 1; i >= 0; i--) { output[count[array[i]] - 1] = array[i]; count[array[i]]--; } // Copy the sorted elements into original array for (int i = 0; i < size; i++) { array[i] = output[i]; } } // Driver code public static void main(String args[]) { int[] data = { 4, 2, 2, 8, 3, 3, 1 }; int size = data.length; CountingSort cs = new CountingSort(); cs.countSort(data, size); System.out.println("Sorted Array in Ascending Order: "); System.out.println(Arrays.toString(data)); } }

**C**

// Counting sort in C programming #include <stdio.h> void countingSort(int array[], int size) { int output[10]; // Find the largest element of the array int max = array[0]; for (int i = 1; i < size; i++) { if (array[i] > max) max = array[i]; } // The size of count must be at least (max+1) but // we cannot declare it as int count(max+1) in C as // it does not support dynamic memory allocation. // So, its size is provided statically. int count[10]; // Initialize count array with all zeros. for (int i = 0; i <= max; ++i) { count[i] = 0; } // Store the count of each element for (int i = 0; i < size; i++) { count[array[i]]++; } // Store the cummulative count of each array for (int i = 1; i <= max; i++) { count[i] += count[i - 1]; } // Find the index of each element of the original array in count array, and // place the elements in output array for (int i = size - 1; i >= 0; i--) { output[count[array[i]] - 1] = array[i]; count[array[i]]--; } // Copy the sorted elements into original array for (int i = 0; i < size; i++) { array[i] = output[i]; } } // Function to print an array void printArray(int array[], int size) { for (int i = 0; i < size; ++i) { printf("%d ", array[i]); } printf("\n"); } // Driver code int main() { int array[] = {4, 2, 2, 8, 3, 3, 1}; int n = sizeof(array) / sizeof(array[0]); countingSort(array, n); printArray(array, n); }

**C++**

// Counting sort in C++ programming #include <iostream> using namespace std; void countSort(int array[], int size) { // The size of count must be at least the (max+1) but // we cannot assign declare it as int count(max+1) in C++ as // it does not support dynamic memory allocation. // So, its size is provided statically. int output[10]; int count[10]; int max = array[0]; // Find the largest element of the array for (int i = 1; i < size; i++) { if (array[i] > max) max = array[i]; } // Initialize count array with all zeros. for (int i = 0; i <= max; ++i) { count[i] = 0; } // Store the count of each element for (int i = 0; i < size; i++) { count[array[i]]++; } // Store the cummulative count of each array for (int i = 1; i <= max; i++) { count[i] += count[i - 1]; } // Find the index of each element of the original array in count array, and // place the elements in output array for (int i = size - 1; i >= 0; i--) { output[count[array[i]] - 1] = array[i]; count[array[i]]--; } // Copy the sorted elements into original array for (int i = 0; i < size; i++) { array[i] = output[i]; } } // Function to print an array void printArray(int array[], int size) { for (int i = 0; i < size; i++) cout << array[i] << " "; cout << endl; } // Driver code int main() { int array[] = {4, 2, 2, 8, 3, 3, 1}; int n = sizeof(array) / sizeof(array[0]); countSort(array, n); printArray(array, n); }

## Complexity

### Time Complexities:

There are predominantly four main loops. (Finding the greatest value should be possible external the function.)

for-loop | time of counting |

1st | O(max) |

2nd | O(size) |

3rd | O(max) |

4th | O(size) |

Overall complexity = O(max)+O(size)+O(max)+O(size) = O(max+size)

**Worst Case Complexity:**O(n+k)**Best Case Complexity:**O(n+k)**Average Case Complexity:**O(n+k)

Altogether the above cases, the complexity is the equivalent on the grounds that no matter how the elements are set in the array, the algorithm goes through n+k times.

There is no comparison between any elements, so it is superior to comparison-based sorting methods. Yet, it is terrible if the integers are enormous on the grounds that the array of that size ought to be made.

### Space Complexity:

The space complexity of Counting Sort is O(max). The larger the range of elements, the larger is the space complexity.

## Counting Sort Applications

Counting sort is used when:

- there are smaller integers with multiple counts.
- linear complexity is the need.

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.