按降序进行计数排序



这是一个有点愚蠢的问题,但每当我试图反转逻辑时,我都会收到索引错误。

如何反转递增计数排序算法?

这是我的代码,它可以升序排序:

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

根据Thomas Weller的建议,

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

相关内容

  • 没有找到相关文章

最新更新