Sorting is one of the fundamental skills every programmer should master. Among the many sorting algorithms, Counting Sort stands out for its simplicity and efficiency in sorting numbers within a limited range. Unlike traditional sorting methods that rely on comparisons, Counting Sort works by counting the frequency of each element and then placing them in order. This makes it exceptionally fast for specific types of data.
 
    
    
    with hands-on learning.
get the skills and confidence to land your next move.
Python is widely loved for its simplicity and readability, making it an excellent language to learn sorting algorithms. Understanding Counting Sort in Python helps beginners not only strengthen their grasp of algorithmic thinking but also lays the foundation for tackling more advanced techniques. In this article, we will walk through multiple ways to implement Counting Sort in Python, from simple loops to recursion and handling negative numbers. By the end, you will have a solid understanding and practical examples to try on your own.
Program 1: Basic Counting Sort for Positive Integers
This program demonstrates the standard Counting Sort algorithm for a list of positive integers. It counts the frequency of each element and arranges them in order.
def counting_sort(arr):
    if len(arr) == 0:
        return arr
    max_value = max(arr)
    count = [0] * (max_value + 1)
    for num in arr:
        count[num] += 1
    sorted_arr = []
    for i, freq in enumerate(count):
        sorted_arr.extend([i] * freq)
    return sorted_arr
numbers = [4, 2, 2, 8, 3, 3, 1]
sorted_numbers = counting_sort(numbers)
print("Sorted list:", sorted_numbers)In this program, a count array stores how many times each number appears. Then, the sorted list is constructed by repeating each number according to its count. Beginners can see how Counting Sort efficiently organizes data without comparisons, making it faster than simple comparison-based sorts for small integer ranges.
Program 2: Counting Sort for Integers Including Zero
Counting Sort can handle zero as well as other positive integers. This program demonstrates a slightly modified version that ensures all numbers, including zero, are correctly sorted.
def counting_sort_with_zero(arr):
    if len(arr) == 0:
        return arr
    max_value = max(arr)
    count = [0] * (max_value + 1)
    for num in arr:
        count[num] += 1
    sorted_arr = []
    for i in range(len(count)):
        for _ in range(count[i]):
            sorted_arr.append(i)
    return sorted_arr
numbers = [0, 5, 2, 0, 3, 2, 1]
sorted_numbers = counting_sort_with_zero(numbers)
print("Sorted list including zero:", sorted_numbers)This version explicitly iterates over the count array to append elements to the sorted list. Beginners can understand that Counting Sort works efficiently for datasets containing zero, emphasizing the importance of carefully constructing the count array for all possible values in the range.
Program 3: Counting Sort for Negative and Positive Integers
Counting Sort can be adapted to handle both negative and positive integers by shifting the values so that all numbers become non-negative. This program demonstrates that approach.
def counting_sort_negative(arr):
    if len(arr) == 0:
        return arr
    min_value = min(arr)
    max_value = max(arr)
    range_size = max_value - min_value + 1
    count = [0] * range_size
    for num in arr:
        count[num - min_value] += 1
    sorted_arr = []
    for i, freq in enumerate(count):
        sorted_arr.extend([i + min_value] * freq)
    return sorted_arr
numbers = [-5, -10, 0, -3, 8, 5, -1, 10]
sorted_numbers = counting_sort_negative(numbers)
print("Sorted list with negative numbers:", sorted_numbers)Here, all numbers are shifted by subtracting the minimum value so they fit into a non-negative count array. This adaptation allows Counting Sort to handle negative numbers as well. Beginners can appreciate how small modifications make the algorithm versatile without changing its fundamental approach.
Program 4: Counting Sort Using a Separate Output Array
This approach introduces a separate output array to ensure the original data is preserved until sorting completes. This method is especially useful when stability is important.
def counting_sort_with_output(arr):
    max_val = max(arr)
    count = [0] * (max_val + 1)
    output = [0] * len(arr)
    for num in arr:
        count[num] += 1
    for i in range(1, len(count)):
        count[i] += count[i - 1]
    for num in reversed(arr):
        output[count[num] - 1] = num
        count[num] -= 1
    for i in range(len(arr)):
        arr[i] = output[i]
numbers = [4, 2, 2, 8, 3, 3, 1]
print("Original List:", numbers)
counting_sort_with_output(numbers)
print("Sorted List:", numbers)Here, the separate output array allows us to preserve the order of equal elements, making the sort stable. This example helps beginners understand cumulative counts and how each element’s position can be determined before writing it into the sorted array.
Program 5: Counting Sort Using Recursion
Recursion is a key concept in programming, and it can also be applied to Counting Sort. This version replaces loops with recursive calls to process the counting array.
def counting_sort_recursive(arr, max_val):
    count = [0] * (max_val + 1)
    for num in arr:
        count[num] += 1
    index = [0]
    def place_elements(i):
        if i >= len(count):
            return
        while count[i] > 0:
            arr[index[0]] = i
            index[0] += 1
            count[i] -= 1
        place_elements(i + 1)
    place_elements(0)
numbers = [4, 2, 2, 8, 3, 3, 1]
print("Original List:", numbers)
counting_sort_recursive(numbers, max(numbers))
print("Sorted List:", numbers)In this recursive example, we use a helper function to iterate through the counting array. Beginners can see how recursion replaces loops while maintaining the same sorting logic. It’s a great way to practice recursive thinking while still working with a familiar algorithm.
Program 6: Counting Sort for Strings
Counting Sort can also be applied to strings or characters. This example shows how to sort a string alphabetically while maintaining stability.
def counting_sort_string(s):
    count = [0] * 256
    output = [''] * len(s)
    for char in s:
        count[ord(char)] += 1
    for i in range(1, len(count)):
        count[i] += count[i - 1]
    for char in reversed(s):
        output[count[ord(char)] - 1] = char
        count[ord(char)] -= 1
    print(''.join(output))
text = "pythoncount"
print("Original String:", text)
print("Sorted String:", end=" ")
counting_sort_string(text)This approach treats each character as its ASCII value, then uses counting logic to sort them. Beginners can see that Counting Sort is versatile and not limited to numbers, making it useful for sorting text or datasets with character codes.
Frequently Asked Questions (FAQ)
Counting Sort often raises common questions for beginners. Here are some answers to help clarify its usage.
Q1: When is Counting Sort faster than other sorting algorithms?
Counting Sort is very efficient when the range of input numbers is small compared to the size of the array. It often outperforms comparison-based sorts like Bubble Sort or Quick Sort in these scenarios.
Q2: Can Counting Sort handle negative numbers?
Yes. By adjusting the counting array to shift the minimum number to zero, negative numbers can be sorted efficiently.
Q3: Is Counting Sort stable?
Yes. By using a separate output array, Counting Sort preserves the relative order of equal elements, ensuring stability.
Q4: Can Counting Sort be used for strings?
Absolutely. By converting characters to their ASCII values, Counting Sort can alphabetically sort strings while maintaining order.
Q5: When should I avoid using Counting Sort?
Counting Sort is not memory-efficient for large ranges of numbers. If the maximum value is very large compared to the array size, it can consume excessive memory and become impractical.
Conclusion
Counting Sort is a simple, efficient, and beginner-friendly sorting algorithm. In Python, we can implement it using loops, recursion, negative number handling, and even for sorting strings. Each example provides a practical way to understand counting logic, cumulative counts, and stable sorting.
By practicing these examples, beginners can strengthen their Python programming skills and gain confidence in algorithmic thinking. Counting Sort serves as a foundation for more advanced sorting techniques, so experimenting with different datasets and variations is an excellent way to improve. Try implementing it on your own lists, and see how versatile and fast it can be!


 
                             
                             
                            


