【发布时间】:2015-11-24 18:50:38
【问题描述】:
下面是一个通过基数排序方法进行排序的程序,但它并没有为每个输入显示正确的输出。
def RadixSort(A):
RADIX = 10
maxLength = False
tmp , placement = -1, 1
while not maxLength:
maxLength = True
buckets = [list() for _ in range(RADIX)]
for i in A:
tmp = i / placement
buckets[tmp % RADIX].append(i)
if maxLength and tmp > 0:
maxLength = False
a = 0
for b in range(RADIX):
buck = buckets[b]
for i in buck:
A[a] = i
a += 1
placement *= RADIX
return A
A = []
n = input("Enter the numebr of elements you want to sort : ")
n = int(n)
print("Enter the numbers : \n")
for i in range(0, n):
num = int(input())
A.append(num)
print(RadixSort(A))
下面给出了几个输入/输出案例的例子:-
Enter the numebr of elements you want to sort : 5
Enter the numbers :
5
4
3
2
1
[1, 2, 3, 4, 5]
这里我们得到了正确的输出,但是在考虑下面的情况时,我们得到了错误的输出
Enter the numebr of elements you want to sort : 9
Enter the numbers :
50
41
700
96
4
00
4
6
852
[50, 700, 0, 41, 852, 4, 4, 96, 6]
我正在尝试解决问题,但无法找到确切的问题。
【问题讨论】:
-
这是 python 2 还是 3?
-
最明显的调试策略是在每次循环后打印出列表,和/或桶列表。
标签: python sorting radix-sort