14_sorts by golang
This commit is contained in:
parent
58e8ec469b
commit
09b6461396
33
go/14_sorts/CountingSort.go
Normal file
33
go/14_sorts/CountingSort.go
Normal file
@ -0,0 +1,33 @@
|
||||
package _4_sorts
|
||||
|
||||
import "math"
|
||||
|
||||
func CountingSort(a []int, n int) {
|
||||
if n <= 1 {
|
||||
return
|
||||
}
|
||||
|
||||
var max int = math.MinInt32
|
||||
for i := range a {
|
||||
if a[i] > max {
|
||||
max = a[i]
|
||||
}
|
||||
}
|
||||
|
||||
c := make([]int, max+1)
|
||||
for i := range a {
|
||||
c[a[i]]++
|
||||
}
|
||||
for i := 1; i <= max; i++ {
|
||||
c[i] += c[i-1]
|
||||
}
|
||||
|
||||
r := make([]int, n)
|
||||
for i := range a {
|
||||
index := c[a[i]] - 1
|
||||
r[index] = a[i]
|
||||
c[a[i]]--
|
||||
}
|
||||
|
||||
copy(a, r)
|
||||
}
|
13
go/14_sorts/CountingSort_test.go
Normal file
13
go/14_sorts/CountingSort_test.go
Normal file
@ -0,0 +1,13 @@
|
||||
package _4_sorts
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCountingSort(t *testing.T) {
|
||||
arr := []int{5, 4}
|
||||
CountingSort(arr, len(arr))
|
||||
t.Log(arr)
|
||||
|
||||
arr = []int{5, 4, 3, 2, 1}
|
||||
CountingSort(arr, len(arr))
|
||||
t.Log(arr)
|
||||
}
|
Loading…
Reference in New Issue
Block a user