Counting Sort Algorithm with Reverse Option Implementation

  • Share this:

Code introduction


This function implements the counting sort algorithm to sort a list of integers. If the reverse parameter is True, it sorts in descending order.


Technology Stack : list comprehension, built-in functions max and min, list slicing, for loop, conditional statements

Code Type : Sorting Algorithm

Code Difficulty : Intermediate


                
                    
def aord(n, reverse=False):
    """
    Sorts a list of numbers using the counting sort algorithm.

    Args:
        n (list): List of integers to be sorted.
        reverse (bool): If True, sort in descending order. Defaults to False.

    Returns:
        list: Sorted list of integers.
    """
    if not n:
        return []

    max_val = max(n)
    min_val = min(n)
    range_val = max_val - min_val + 1

    count = [0] * range_val
    output = [0] * len(n)

    for num in n:
        count[num - min_val] += 1

    if reverse:
        start = range_val - 1
        end = -1
        step = -1
    else:
        start = 0
        end = len(n) - 1
        step = 1

    for i in range(range_val - 1, -1, -1):
        count[i] += count[i + 1]
        for _ in range(count[i]):
            output[start] = i + min_val
            start += step

    return output