From 1021034f18544217163f000bedc77b92fcdbccc5 Mon Sep 17 00:00:00 2001 From: yubaozhu Date: Fri, 28 May 2021 15:35:51 +0800 Subject: [PATCH] sort --- go/14_sorts/CountingSort.go | 2 +- go/14_sorts/CountingSort_test.go | 2 +- go/14_sorts/bucketSort.go | 47 ++++++++++++++++++++++++++++++ go/14_sorts/radixSort.go | 49 ++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 go/14_sorts/bucketSort.go create mode 100644 go/14_sorts/radixSort.go diff --git a/go/14_sorts/CountingSort.go b/go/14_sorts/CountingSort.go index 0fbb2f70..d4d993a2 100644 --- a/go/14_sorts/CountingSort.go +++ b/go/14_sorts/CountingSort.go @@ -1,4 +1,4 @@ -package _4_sorts +package _14_sorts import "math" diff --git a/go/14_sorts/CountingSort_test.go b/go/14_sorts/CountingSort_test.go index c6f5b466..846c2696 100644 --- a/go/14_sorts/CountingSort_test.go +++ b/go/14_sorts/CountingSort_test.go @@ -1,4 +1,4 @@ -package _4_sorts +package _14_sorts import "testing" diff --git a/go/14_sorts/bucketSort.go b/go/14_sorts/bucketSort.go new file mode 100644 index 00000000..882dae02 --- /dev/null +++ b/go/14_sorts/bucketSort.go @@ -0,0 +1,47 @@ +package _14_sorts + +import "math" + +func bucketSort(arr []int) { + minNum,maxNum,n:=math.MaxInt32,math.MinInt32,len(arr) + for i := 0; i y { + return x + } + return y +} +func min (x,y int)int{ + if x>y { + return y + } + return x +} \ No newline at end of file diff --git a/go/14_sorts/radixSort.go b/go/14_sorts/radixSort.go new file mode 100644 index 00000000..1300f213 --- /dev/null +++ b/go/14_sorts/radixSort.go @@ -0,0 +1,49 @@ +package _14_sorts + +import "math" + +func radixSort(arr []int) { + n := len(arr) + if n <= 1 { + return + } + d := maxbit(arr) + radix := 1 + var k int + count, newArr := make([]int, 10), make([]int, n) + for d >= 1 { + for i := 0; i < 10; i++ { + count[i] = 0 + } + for i := 0; i < n; i++ { + k = (arr[i] / radix) % 10 + count[k]++ + } + for i := 1; i < 10; i++ { + count[i] += count[i-1] + } + for i := n - 1; i >= 0; i-- { + k = (arr[i] / radix) % 10 + newArr[count[k]-1] = arr[i] + count[k]-- + } + d-- + radix *= 10 + copy(arr, newArr) + } + +} +func maxbit(arr []int) int { + maxNum := math.MinInt32 + for _, val := range arr { + if val > maxNum { + maxNum = val + } + } + d := 1 + for maxNum >= 10 { + d++ + maxNum /= 10 + } + return d +}