Welcome to your journey into the world of sorting algorithms! Today, we're diving deep into Counting Sort, a powerful and efficient sorting technique that's perfect for beginners and intermediates alike. Let's get started!
Counting Sort is a simple yet effective sorting algorithm that works well with data sets that are small in size but have a large range of values. It's based on the frequency of values in a list and is particularly useful when you can represent the input data in an array or a list of integers.
š” Pro Tip: Counting Sort is not suitable for data sets with large ranges (e.g., floating-point numbers with a large number of digits). For such cases, consider using other sorting algorithms like Quick Sort, Merge Sort, or Heap Sort.
Let's break down the Counting Sort algorithm into easy-to-understand steps:
Initialize an array C of size equal to the maximum possible value of the input data. Fill this array with zeros. This array will be used to count the frequency of each value in the input data.
Iterate through the input data and for each value, increment the corresponding index in the C array.
Initialize another array B with the same size as the input data. This array will hold the sorted output.
Iterate through the C array and use the count values to place the sorted elements in the B array.
Return the B array, which now contains the sorted input data.
Here's a complete example to help you understand better:
def counting_sort(arr, max_val):
# Step 1: Initialize C array with zeros
C = [0] * (max_val + 1)
# Step 2: Count occurrences of each value in arr
for val in arr:
C[val] += 1
# Step 3: Initialize B array with zeros
B = [0] * len(arr)
# Step 4: Place sorted elements in B array
for i in range(max_val, -1, -1):
for j in range(C[i], len(arr)):
B[j] = i
C[i] -= len(arr)
# Step 5: Return the sorted array B
return Bš Note: Make sure to pass the maximum value of the input data as an argument to the function.
Now that you've learned about Counting Sort, let's test your understanding with a quiz:
Given an input array [9, 4, 7, 5, 2, 6, 1, 3, 8], what would the output of the counting_sort function be, if we pass 9 as the maximum value?
And that's a wrap for today! With a solid understanding of Counting Sort, you're one step closer to mastering essential data structures and algorithms. Keep learning, practicing, and coding! š
Stay tuned for more advanced sorting algorithms and practical examples in upcoming lessons. Happy coding! šÆ