Python algorithm to learn the radix sort example

  • 2020-04-02 13:17:29
  • OfStack

Radix sort method is also called the bucket method (bucket sort) or bin sort, as the name implies, it is through the key part of the information, will sort of element distribution to some "bucket", so as to achieve sort, radix sort method belongs to the stability of sorting, its time complexity is O (nlog (r) (m), in which r is taken by the base, and m for the pile number, at some point, the efficiency of the method of radix sort is higher than other comparative sorting method.


# -*- coding: utf-8 -*-
def _counting_sort(A, i):
    """ Count sort to i Bit sort to apply to radix sort. 
    Args:
        A (Sequence):  Sort an array 
        i (int):  Figures from the 0 Start instead of 1
    """
    C = [0] * 10 #  The range of arbitrary values is [0,9]
    A = [(a / (10 ** i) % 10, a) for a in A] #  The element i An array of bits and their own tuples 
    for k, a in A:
        C[k] = C[k] + 1
    for i in xrange(1, 10):
        C[i] = C[i] + C[i-1]
    B = [0] * len(A) #  The result array 
    for k, a in A[::-1]:
        B[C[k]-1] = a
        C[k] = C[k] - 1
    return B
def radix_sort(A, d):
    """ Radix sort, from the lowest order to the highest bit: 
    RADIX-SORT(A, d)
    1  for i  please  1 to d
    2    do use a stable sort to sort array A on digit i
    Args:
        A (Sequence):  Sort an array 
        d (int):  Maximum digit 
    """
    for i in xrange(d): #  Traversing the number of digits, from low to high 
        A = _counting_sort(A, i)
    return A
def rsort(A, d):
    """ Radix sort (bucket sort version) """
    for i in xrange(d): #  Traversing the number of digits, from low to high 
        S = [[] for _ in xrange(10)] #  store [0,9] The element ( [0-9]10 A barrel) 
        for a in A: #  Traverse elements 
            S[a / (10 ** i) % 10].append(a) #  Store the element with the corresponding bit value (the bucket in which the current bit value of the element is placed) 
        A = [a for b in S for a in b] #  Sorted by the current bit value A (take the elements out of each bucket in turn) 
    return A
if __name__ == '__main__':
    import random, timeit
    items = range(10000)
    random.shuffle(items)
    def test_sorted():
        print(items)
        sorted_items = sorted(items)
        print(sorted_items)
    def test_radix_sort():
        print(items)
        sorted_items = radix_sort(items, 4) # [0,9999] . 4 digits 
        print(sorted_items)
    test_methods = [test_sorted, test_radix_sort]
    for test in test_methods:
        name = test.__name__ # test.func_name
        t = timeit.Timer(name + '()', 'from __main__ import ' + name)
        print(name + ' takes time : %f' % t.timeit(1))


Related articles: