# Radixsort for positive integers. (1.01) def iterations(a, b): x = max(a) r = 0 while x != 0: x //= b r += 1 return r def radixsorted(a): if not a: return [] n = len(a) a = a.copy() b = [None] * n k = 16 # Number of buckets (not limited to powers of two). for i in range(iterations(a, k)): d = k**i g = lambda x: x // d % k # Extract key. h = [0] * k # Histogram. for x in a: h[g(x)] += 1 # Accumulate positions. for j in range(1, k): h[j] += h[j-1] # Reorder. for x in reversed(a): j = g(x) h[j] -= 1 b[h[j]] = x a, b = b, a return a # Test. from random import choices n = 11 for i in range(n): m = 2**i-1 a = choices(range(m), k=m) u = sorted(a) v = radixsorted(a) if u == v: print('Pass:', m) else: print('Fail:', (m, u, v)) # Show. n = 10 a = choices(range(n), k=n) print(a) print(sorted(a)) print(radixsorted(a))
Standard input is empty
Pass: 0 Pass: 1 Pass: 3 Pass: 7 Pass: 15 Pass: 31 Pass: 63 Pass: 127 Pass: 255 Pass: 511 Pass: 1023 [6, 3, 7, 5, 5, 6, 0, 6, 7, 3] [0, 3, 3, 5, 5, 6, 6, 6, 7, 7] [0, 3, 3, 5, 5, 6, 6, 6, 7, 7]