Counting sort in descending order

1k Views Asked by At

This is a bit of a dumb question, but I keep receiving indexing errors whenever I attempt to reverse my logic.

How do I reverse an ascending counting sort algorithm?

Here is my code, which is able to sort ascendingly:

def count_sort(arr: StaticArray) -> StaticArray:
    """
    TODO: Write this implementation
    """
    # The output array that will have sorted arr
    new_arr = StaticArray(arr.size())
    # The count array that will store count of individual characters
    count = StaticArray(1000)
    for zero in range(count.size()):
        count.set(zero, 0)
    # identify the minimum number in the array
    min_element = arr[0]
    ind = 1
    while ind <= arr.size() - 1:
        if arr[ind] < min_element:
            min_element = arr[ind]
        ind += 1

    for i in range(0, arr.size()):
        count[arr[i] - min_element] += 1
   
    for j in range(1, 1000):
        count[j] += count[j-1]
    
    i = arr.size() - 1

    while i >= 0:
        new_arr[count[arr[i] - min_element] - 1] = arr[i]
        count[arr[i] - min_element] -=  1
        i -= 1

    return new_arr
1

There are 1 best solutions below

0
On

per Thomas Weller's suugestion,

def count_sort(arr: StaticArray, directio: str) -> StaticArray:
.
.
.
if direction == 'Reverse':
    return new_arr[::-1]
return new_arr