Add the section of radix sort. (#441)

This commit is contained in:
Yudong Jin
2023-03-26 22:02:37 +08:00
committed by GitHub
parent 4830dffd26
commit 34a1bca627
16 changed files with 405 additions and 142 deletions

View File

@ -14,29 +14,29 @@ func digit(num, exp int) int {
/* 计数排序(根据 nums 第 k 位排序) */
func countingSortDigit(nums []int, exp int) {
// 十进制的各位数字范围为 0~9 ,因此需要长度为 10 的桶
bucket := make([]int, 10)
// 十进制的范围为 0~9 ,因此需要长度为 10 的桶
counter := make([]int, 10)
n := len(nums)
// 借助桶来统计 0~9 各数字的出现次数
// 统计 0~9 各数字的出现次数
for i := 0; i < n; i++ {
d := digit(nums[i], exp) // 获取 nums[i] 第 k 位,记为 d
bucket[d]++ // 统计数字 d 的出现次数
counter[d]++ // 统计数字 d 的出现次数
}
// 求前缀和,将“出现个数”转换为“数组索引”
for i := 1; i < 10; i++ {
bucket[i] += bucket[i-1]
counter[i] += counter[i-1]
}
// 倒序遍历,根据桶内统计结果,将各元素填入暂存数组 tmp
tmp := make([]int, n)
// 倒序遍历,根据桶内统计结果,将各元素填入 res
res := make([]int, n)
for i := n - 1; i >= 0; i-- {
d := digit(nums[i], exp)
j := bucket[d] - 1 // 获取 d 在数组中的索引 j
tmp[j] = nums[i] // 将当前元素填入索引 j
bucket[d]-- // 将 d 的数量减 1
j := counter[d] - 1 // 获取 d 在数组中的索引 j
res[j] = nums[i] // 将当前元素填入索引 j
counter[d]-- // 将 d 的数量减 1
}
// 将 tmp 复制到 nums
// 使用结果覆盖原数组 nums
for i := 0; i < n; i++ {
nums[i] = tmp[i]
nums[i] = res[i]
}
}
@ -51,10 +51,9 @@ func radixSort(nums []int) {
}
// 按照从低位到高位的顺序遍历
for exp := 1; max >= exp; exp *= 10 {
// 对数组元素的第 k 位执行计数排序
// 对数组元素的第 k 位执行计数排序
// k = 1 -> exp = 1
// k = 2 -> exp = 10
// k = 3 -> exp = 100
// 即 exp = 10^(k-1)
countingSortDigit(nums, exp)
}

View File

@ -11,7 +11,8 @@ import (
func TestRadixSort(t *testing.T) {
/* 基数排序 */
nums := []int{23, 12, 3, 4, 788, 192}
nums := []int{10546151, 35663510, 42865989, 34862445, 81883077,
88906420, 72429244, 30524779, 82060337, 63832996}
radixSort(nums)
fmt.Println("基数排序完成后 nums = ", nums)
}