Counting Sort Algorithm
In this tutorial, you will learn how counting sort works. Also, you will find working examples of counting sort in Python.
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.
How Counting Sort Works?
- 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
arrayFor 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.
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 Examples
/* 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)
Complexity
Time Complexities:
There are mainly four main loops. (Finding the greatest value can be done outside 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)
In all the above cases, the complexity is the same because no matter how the elements are placed in the array, the algorithm goes through n+k
times.
There is no comparison between any elements, so it is better than comparison based sorting techniques. But, it is bad if the integers are very large because the array of that size should be made.
Space Complexity:
The space complexity of Counting Sort is O(max)
. Larger the range of elements, 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.
Python Example for Beginners
Two Machine Learning Fields
There are two sides to machine learning:
- Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
- Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.
Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes
Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!
Latest end-to-end Learn by Coding Recipes in Project-Based Learning:
Applied Statistics with R for Beginners and Business Professionals
Data Science and Machine Learning Projects in Python: Tabular Data Analytics
Data Science and Machine Learning Projects in R: Tabular Data Analytics
Python Machine Learning & Data Science Recipes: Learn by Coding
R Machine Learning & Data Science Recipes: Learn by Coding
Comparing Different Machine Learning Algorithms in Python for Classification (FREE)
Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.