基數排序

基數排序,是基於計數排序的穩定排序。對於元素的每一位進行排序,例如十進制的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]
	}
}

測試代碼即main包代碼:

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)
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章