2020-10-29 00:09:39 -03:00
|
|
|
"""
|
2022-10-01 17:47:15 +05:30
|
|
|
This is a pure Python implementation of the radix sort algorithm
|
|
|
|
|
|
|
|
Source: https://en.wikipedia.org/wiki/Radix_sort
|
2020-10-29 00:09:39 -03:00
|
|
|
"""
|
2020-09-23 13:30:13 +02:00
|
|
|
from __future__ import annotations
|
2017-09-29 23:47:24 +02:00
|
|
|
|
2022-10-16 10:33:29 +01:00
|
|
|
RADIX = 10
|
|
|
|
|
2017-09-29 23:47:24 +02:00
|
|
|
|
2021-09-07 13:37:03 +02:00
|
|
|
def radix_sort(list_of_ints: list[int]) -> list[int]:
|
2020-06-23 15:37:24 +02:00
|
|
|
"""
|
2020-10-29 00:09:39 -03:00
|
|
|
Examples:
|
|
|
|
>>> radix_sort([0, 5, 3, 2, 2])
|
|
|
|
[0, 2, 2, 3, 5]
|
|
|
|
|
|
|
|
>>> radix_sort(list(range(15))) == sorted(range(15))
|
2020-06-23 15:37:24 +02:00
|
|
|
True
|
2020-10-29 00:09:39 -03:00
|
|
|
>>> radix_sort(list(range(14,-1,-1))) == sorted(range(15))
|
2020-06-23 15:37:24 +02:00
|
|
|
True
|
2020-10-29 00:09:39 -03:00
|
|
|
>>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
|
2020-09-01 00:55:56 +08:00
|
|
|
True
|
2020-06-23 15:37:24 +02:00
|
|
|
"""
|
|
|
|
placement = 1
|
|
|
|
max_digit = max(list_of_ints)
|
2020-09-01 00:55:56 +08:00
|
|
|
while placement <= max_digit:
|
2020-06-23 15:37:24 +02:00
|
|
|
# declare and initialize empty buckets
|
2022-10-15 18:29:42 +01:00
|
|
|
buckets: list[list] = [[] for _ in range(RADIX)]
|
2020-06-23 15:37:24 +02:00
|
|
|
# split list_of_ints between the buckets
|
|
|
|
for i in list_of_ints:
|
2019-10-05 01:14:13 -04:00
|
|
|
tmp = int((i / placement) % RADIX)
|
|
|
|
buckets[tmp].append(i)
|
2020-06-23 15:37:24 +02:00
|
|
|
# put each buckets' contents into list_of_ints
|
2019-10-05 01:14:13 -04:00
|
|
|
a = 0
|
|
|
|
for b in range(RADIX):
|
2020-06-23 15:37:24 +02:00
|
|
|
for i in buckets[b]:
|
|
|
|
list_of_ints[a] = i
|
2019-10-05 01:14:13 -04:00
|
|
|
a += 1
|
|
|
|
# move to next
|
|
|
|
placement *= RADIX
|
2020-06-23 15:37:24 +02:00
|
|
|
return list_of_ints
|
2020-10-29 00:09:39 -03:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|