【问题标题】:Counting sort in descending order [closed]按降序计数排序[关闭]
【发布时间】:2021-04-21 08:13:20
【问题描述】:

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

如何反转升序计数排序算法?

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

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

【问题讨论】:

  • “但每当我试图反转我的逻辑时,我都会收到索引错误。”我们只能告诉您实际显示的代码有什么问题。向我们展示工作版本并没有什么好处,然后询问一些不起作用并且只是模糊描述的东西。
  • 排序后,为什么不简单地反转整个事情呢?

标签: python python-3.x algorithm data-structures counting-sort


【解决方案1】:

根据Thomas Weller的建议,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多