Im trying to implement Radix Sort in Python. In the main Radix Sort function there is a for loop like this:
JavaScript
x
6
1
m = Maximum element in a given array
2
for(p = 1; m/p > 0; p*10)
3
{
4
do stuff;
5
}
6
i did implement it using a while loop like below:
JavaScript
1
5
1
p = 1
2
while m / p > 0:
3
p *= 10
4
do stuff;
5
But since for loop is faster than while loop, I wonder how to implement that pseudocode in Python with a for loop. Any suggestions?
Note: Radix Sort uses counting sort to sort based on digits starting from the right most digit (p=1) to the last digit and that’s why for loop is used.
Advertisement
Answer
Well after doing a research on the loops topic, i found that using a string instead of doing calculation is much faster. It is not the correct answer but it is the fastest implementation in Python.
JavaScript
1
4
1
for _ in range(len(str(m)):
2
do stuff
3
4