algorithm-in-python/sort/radixSort.py

57 lines
1.4 KiB
Python
Raw Normal View History

2018-07-08 23:28:29 +08:00
''' mbinary
#########################################################################
# File : radixSort.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# Blog: https://mbinary.xyz
2018-07-08 23:28:29 +08:00
# Github: https://github.com/mbinary
# Created Time: 2018-07-06 15:52
# Description:
#########################################################################
'''
2020-04-15 12:28:20 +08:00
from random import randint
from quickSort import quickSort
from time import time
def radixSort(lst, radix=10):
2018-07-08 16:41:55 +08:00
ls = [[] for i in range(radix)]
mx = max(lst)
2020-04-15 12:28:20 +08:00
weight = 1
2018-07-08 16:41:55 +08:00
while mx >= weight:
for i in lst:
2020-04-15 12:28:20 +08:00
ls[(i // weight) % radix].append(i)
2018-07-08 16:41:55 +08:00
weight *= radix
2020-04-15 12:28:20 +08:00
lst = sum(ls, [])
ls = [[] for i in range(radix)]
2018-07-08 16:41:55 +08:00
return lst
2020-04-15 12:28:20 +08:00
def countSort(lst, mn, mx):
2018-07-08 16:41:55 +08:00
mark = [0]*(mx-mn+1)
for i in lst:
2020-04-15 12:28:20 +08:00
mark[i-mn] += 1
ret = []
for n, i in enumerate(mark):
ret += [n+mn]*i
2018-07-08 16:41:55 +08:00
return ret
2020-04-15 12:28:20 +08:00
def timer(funcs, span, num=1000000):
lst = [randint(0, span) for i in range(num)]
print('range({}), {} items'.format(span, num))
2018-07-08 16:41:55 +08:00
for func in funcs:
data = lst.copy()
t = time()
func(data)
t = time()-t
2020-04-15 12:28:20 +08:00
print('{}: {}s'.format(func.__name__, t))
2018-07-08 16:41:55 +08:00
if __name__ == '__main__':
2020-04-15 12:28:20 +08:00
timer([quickSort, radixSort, sorted], 1000000000000, 1000)
timer([quickSort, radixSort, sorted], 10000, 100000)
lst = [randint(0, 100) for i in range(1000)]
print(countSort(lst, 0, 100) == sorted(lst))