基数排序,是基于计数排序的稳定排序。对于元素的每一位进行排序,例如十进制的101,100,111从个位先计数排序,再十位计数排序,最后百位上计数排序。
当然也并一定是按十进制来进行排序,可以按任何进制进行排序。
时间复杂度为O(k * n),k为位数;空间复杂度为O(radix + n),radix为计数所用的桶,比如10进制为10,十六进制为16。
golang代码如下:
package algorithms
func RadixSort(slice []int, countBase, divideLength int) {
sortMap := divideSlices(slice, countBase, divideLength)
//sortMap := make(map[int]int)
for index := 0; index != divideLength; index ++ {
countSortWithMap(sortMap, countBase, slice, index)
}
}
func divideSlices(slice []int, countBase, divideLength int)(sortMap map[int][]int) {
sortMap = make(map[int][]int, len(slice))
for _, value := range slice {
sortMap[value] = getSliceFromInt(value, countBase, divideLength)[:divideLength]
}
return sortMap
}
func getSliceFromInt(num, countBase int, divideLength int)(divideSlice []int) {
divideSlice = make([]int, divideLength)
for i := 0; num != 0; i ++ {
divideSlice[i] = num % countBase
num = num / countBase
}
return divideSlice
}
func countSortWithMap(sortMap map[int][]int, countBase int, keySlice []int, index int) {
slice := getIndexSlice(sortMap, keySlice, index)
countSortWithSlice(slice, keySlice, countBase)
}
func getIndexSlice(sortMap map[int][]int, keySlice []int, index int)(slice []int) {
slice = make([]int, len(keySlice))
for i, v := range keySlice {
slice[i] = sortMap[v][index]
}
return slice
}
func countSortWithSlice(slice []int, keySlice []int, countBase int) {
indexSlice := make([]int, countBase)
for _, v := range slice {
indexSlice[v]++
}
for i := 0; i != countBase - 1; i++ {
indexSlice[i + 1] += indexSlice[i]
}
sortedSlice:= make([]int, len(slice))
for reverseIndex := len(keySlice) - 1; reverseIndex >= 0; reverseIndex-- {
indexSlice[slice[reverseIndex]]--
sortedSlice[indexSlice[slice[reverseIndex]]] = keySlice[reverseIndex]
}
for i, _ := range slice {
keySlice[i] = sortedSlice[i]
}
}
package main
import (
"algorithms"
"fmt"
)
func main() {
slice := []int{100, 4, 2, 33, 555, 2, 101, 200, 2, 73, 27, 26, 89, 201, 1001, 500, 201, 451, 6110}
algorithms.RadixSort(slice, 16, 4)
fmt.Println(slice)
}