Python 按降序计数排序
这是一个有点愚蠢的问题,但每当我试图逆转我的逻辑时,我总是收到索引错误 如何反转递增计数排序算法 这是我的代码,它可以按升序排序:Python 按降序计数排序,python,python-3.x,algorithm,data-structures,counting-sort,Python,Python 3.x,Algorithm,Data Structures,Counting Sort,这是一个有点愚蠢的问题,但每当我试图逆转我的逻辑时,我总是收到索引错误 如何反转递增计数排序算法 这是我的代码,它可以按升序排序: def count_sort(arr: StaticArray) -> StaticArray: """ TODO: Write this implementation """ # The output array that will have sorted arr
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
def count\u sort(arr:StaticArray)->StaticArray:
"""
TODO:编写此实现
"""
#将对arr进行排序的输出数组
new_arr=StaticArray(arr.size())
#将存储单个字符计数的计数数组
计数=静态数组(1000)
对于范围内的零(count.size()):
count.set(零,0)
#确定数组中的最小数目
最小元素=arr[0]
ind=1
当ind=0时:
新的arr[count[arr[i]-min\u元素]-1]=arr[i]
计数[arr[i]-最小元素]-=1
i-=1
返回新地址
per的suugestion
def count_sort(arr: StaticArray, directio: str) -> StaticArray:
.
.
.
if direction == 'Reverse':
return new_arr[::-1]
return new_arr
per的suugestion
def count_sort(arr: StaticArray, directio: str) -> StaticArray:
.
.
.
if direction == 'Reverse':
return new_arr[::-1]
return new_arr
“但每当我试图反转逻辑时,我总是收到索引错误。”我们只能告诉您实际显示的代码有什么问题。向我们展示工作版本,然后询问一些不起作用且只是模糊描述的内容是没有好处的。一旦分类,为什么不干脆将整个内容颠倒过来?“但每当我试图颠倒逻辑时,我总是会收到索引错误。”我们只能告诉您实际显示的代码有什么问题。向我们展示工作版本,然后询问一些不起作用且只是模糊描述的内容是没有好处的。一旦分类,为什么不干脆将整个内容颠倒过来呢?