基数排序(radix sort)属于“分配式排序”(distribution sort),又称“桶子法”(bucket sort)或bin sort,顾名思义,它是透过数项(item)的位(digit),将要排序的元素分配至某些“桶”中,藉以达到排序的作用。基数排序法是属于稳定性的排序,其时间复杂度为O (nlog(r)m),其中r为所采取的基数,而m为堆数,在某些时候,基数排序法的效率高于其它的稳定性排序法。
radix sort machine的英文描述为:
A radix sort for base 10 integers is a mechanical sorting technique that utilizes a collection of bins, one main bin and 10 digit bins. Each bin acts like a queue and maintains its values in the order that they arrive. The algorithm begins by placing each number in the main bin. Then it considers each value digit by digit. The first value is removed and placed in a digit bin corresponding to the digit being considered. For example, if the ones digit is being considered, 534 is placed in digit bin 4 and 667 is placed in digit bin 7. Once all the values are placed in the corresponding digit bins, the values are collected from bin 0 to bin 9 and placed back in the main bin. The process continues with the tens digit, the hundreds, and so on. After the last digit is processed, the main bin contains the values in order.
基数排序法的python实现为:
from pythonds.basic.queue import Queue
import math
def radix_sort(num_list, redix=10):
# initialize the main bin and digit bins.
main_bin = Queue()
bins = {}
for i in range(redix):
bins[i] = Queue()
# enqueue the number to main bin.
for num in num_list:
main_bin.enqueue(num)
# gain the number of digits of the max item in list.
n_digit = math.ceil(math.log(max(num_list), redix))
for k in range(1, n_digit + 1):
while not main_bin.isEmpty():
item = main_bin.dequeue()
# gain the kth digit of item.
digit = item % redix**k // redix**(k-1)
bins[digit].enqueue(item)
for j in range(10):
while not bins[j].isEmpty():
main_bin.enqueue(bins[j].dequeue())
return main_bin
def main():
a = [552, 431, 26, 531, 736, 2, 777]
main_bin = radix_sort(a)
while not main_bin.isEmpty():
print(main_bin.dequeue())
main()
其中值得注意的有两点:
1.如何获取一串无序数列表中最大的那个数的位数(十位数–>2、百位数–>3、千位数–>4等),采用的数学思想是:log(item,redix)然后取ceil。
2.如何获取一个数的某位上的数值,例如554这个数,个位数是4,百位千位是5,如何获取他们?数学思想是:item % radix^k // radix^(k-1)。