Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add go radixSort和bucketSort #511

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go/14_sorts/CountingSort.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package _4_sorts
package _14_sorts

import "math"

Expand Down
2 changes: 1 addition & 1 deletion go/14_sorts/CountingSort_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package _4_sorts
package _14_sorts

import "testing"

Expand Down
47 changes: 47 additions & 0 deletions go/14_sorts/bucketSort.go
Original file line number Diff line number Diff line change
@@ -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 <n ; i++ {
maxNum=max(maxNum,arr[i])
minNum=min(minNum,arr[i])
}

//桶数
bucketNum:=(maxNum-minNum)/n+1
bucketArr:=make([][]int,bucketNum)
for i := 0; i <bucketNum ; i++ {
bucketArr[i]=[]int{}
}

//将每个元素放入桶
for i := 0; i < n; i++ {
num := (arr[i] - minNum) / n
bucketArr[num] = append(bucketArr[num], arr[i])
}

k:=0
//对每个桶进行排序
for i := 0; i <bucketNum ; i++ {
//归并
mergeSort(bucketArr[i],0,len(bucketArr[i])-1)
for j := 0; j <len(bucketArr[i]) ; j++ {
arr[k]=bucketArr[i][j]
k++
}
}
}
func max (x,y int)int{
if x>y {
return x
}
return y
}
func min (x,y int)int{
if x>y {
return y
}
return x
}
49 changes: 49 additions & 0 deletions go/14_sorts/radixSort.go
Original file line number Diff line number Diff line change
@@ -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
}