Below is a program that is for sorting through the radix sort method, but it does not show the correct output for every input.
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))
few examples of input / output cases are given below : -
Enter the numebr of elements you want to sort : 5
Enter the numbers :
5
4
3
2
1
[1, 2, 3, 4, 5]
Here we get correct output but while considering the case below we get a wrong output
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]
I'm trying to figure it out but unable to fetch the exact problem.
Well this is a good code, but you did a silly mistake while indenting this placement *= RADIX
As you are using placement *= RADIX
to move to next digit, so it has to be executed out of the for loop
So, the problem was with indenting placement *= RADIX
you can change a little bit of your code to:-
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
# move to next digit
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))