Analysis of the Principle and usage of the base sorting algorithm implemented by Python, and analysis of python instances
This example describes the base sorting algorithm implemented by Python. We will share this with you for your reference. The details are as follows:
Base sorting (radix sort) is a type of "distribution sort", also known as "bucket sort" or "bin sort". As the name suggests, it uses some information about key values, elements to be sorted are allocated to certain "buckets" to achieve sorting. The base sorting method is a stable sorting, and its time complexity is O (nlog (r) m ), r indicates the base number adopted, while m indicates the number of heaps. In some cases, the base sorting method is more efficient than other stability sorting methods.
The implementation code is as follows:
#-*-Coding: UTF-8-*-import numpy as npdef RadixSort (a): I = 0 # initially for single-digit sorting n = 1 # the smallest number of digits is set to 1 (including 0) max = np. max (a) # obtain the largest number of while max/(10 ** n)> 0: # obtain the maximum number of digits n + = 1 while I <n: bucket ={}# build a bucket in the dictionary for x in xrange (): bucket. setdefault (x, []) # Leave each bucket empty for x in a: # Sort each bit radix = (x/(10 ** I )) % 10 # obtain the base bucket [radix] for each bucket. append (x) # Add the corresponding array element to the bucket with the corresponding base number j = 0 for k in xrange (0, 10): if len (bucket [k] )! = 0: # If the bucket is not empty, for y in bucket [k]: # Put each element a [j] = y # in the bucket back to the array j + = 1 I + = 1if _ name _ = '_ main __': a = np. random. randint (0, 1000, size = 10) print "Before sorting... "print a print" ------------------------------------------------------------- "RadixSort (a) print" After sorting... "print" ------------------------------------------------------------- "print a print "---------------------------------------------------------------"
Running result: