From a78365401e7930a77053e82b768c00ddb38ffcf4 Mon Sep 17 00:00:00 2001 From: krahets Date: Mon, 20 Mar 2023 21:40:50 +0800 Subject: [PATCH] Update counting_sort.go and radix_sort.go --- codes/go/chapter_sorting/counting_sort.go | 6 ++++-- .../{count_sort_test.go => counting_sort_test.go} | 5 ++--- codes/go/chapter_sorting/radix_sort.go | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) rename codes/go/chapter_sorting/{count_sort_test.go => counting_sort_test.go} (83%) diff --git a/codes/go/chapter_sorting/counting_sort.go b/codes/go/chapter_sorting/counting_sort.go index d52c6cd2b..5d23334a6 100644 --- a/codes/go/chapter_sorting/counting_sort.go +++ b/codes/go/chapter_sorting/counting_sort.go @@ -8,7 +8,7 @@ type CountingSort struct{} /* 计数排序 */ // 简单实现,无法用于排序对象 -func (c *CountingSort) countingSortNaive(nums []int) { +func countingSortNaive(nums []int) { // 1. 统计数组最大元素 m m := 0 for num := range nums { @@ -31,7 +31,9 @@ func (c *CountingSort) countingSortNaive(nums []int) { } } -func (c *CountingSort) countingSort(nums []int) { +/* 计数排序 */ +// 完整实现,可排序对象,并且是稳定排序 +func countingSort(nums []int) { // 1. 统计数组最大元素 m m := 0 for num := range nums { diff --git a/codes/go/chapter_sorting/count_sort_test.go b/codes/go/chapter_sorting/counting_sort_test.go similarity index 83% rename from codes/go/chapter_sorting/count_sort_test.go rename to codes/go/chapter_sorting/counting_sort_test.go index 8358a9935..cd934275f 100644 --- a/codes/go/chapter_sorting/count_sort_test.go +++ b/codes/go/chapter_sorting/counting_sort_test.go @@ -10,11 +10,10 @@ import ( ) func TestCountingSort(t *testing.T) { - c := &CountingSort{} nums := []int{1, 0, 1, 2, 0, 4, 0, 2, 2, 4} - c.countingSortNaive(nums) + countingSortNaive(nums) fmt.Println("计数排序(无法排序对象)完成后 nums = ", nums) - c.countingSort(nums) + countingSort(nums) fmt.Println("计数排序完成后 nums = ", nums) } diff --git a/codes/go/chapter_sorting/radix_sort.go b/codes/go/chapter_sorting/radix_sort.go index 30756f132..3e4191aea 100644 --- a/codes/go/chapter_sorting/radix_sort.go +++ b/codes/go/chapter_sorting/radix_sort.go @@ -13,7 +13,7 @@ func digit(num, exp int) int { } /* 计数排序(根据 nums 第 k 位排序) */ -func countingSort(nums []int, exp int) { +func countingSortDigit(nums []int, exp int) { // 十进制的各位数字范围为 0~9 ,因此需要长度为 10 的桶 bucket := make([]int, 10) n := len(nums) @@ -56,6 +56,6 @@ func radixSort(nums []int) { // k = 2 -> exp = 10 // k = 3 -> exp = 100 // 即 exp = 10^(k-1) - countingSort(nums, exp) + countingSortDigit(nums, exp) } }