基數(shù)排序算法是桶排序算法的一種,是對(duì)基于相同位置的值,進(jìn)行分組排序。可能這么說有點(diǎn)不好理解,可以看下面的基數(shù)排序算法原理實(shí)例。
基數(shù)排序算法原理實(shí)例
指定數(shù)組[121,432,564,23,1,45,788],將數(shù)組進(jìn)行基數(shù)排序,如圖:
先進(jìn)行個(gè)位數(shù)值的排序,再進(jìn)行十位數(shù)值的排序,最后再排序百位數(shù)值,最后輸出經(jīng)過排序后的數(shù)組為[001,023,045,121,432,564,788]
Python代碼實(shí)現(xiàn)基數(shù)排序算法
def countingSort(array, place): size = len(array) output = [0] * size count = [0] * 10 for i in range(0, size): index = array[i] // place count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = size - 1 while i >= 0: index = array[i] // place output[count[index % 10] - 1] = array[i] count[index % 10] -= 1 i -= 1 for i in range(0, size): array[i] = output[i] def radixSort(array): # Get maximum element max_element = max(array) place = 1 while max_element // place > 0: countingSort(array, place) place *= 10 data = [121, 432, 564, 23, 1, 45, 788] radixSort(data) print(data)
登錄后復(fù)制