14_sorts by golang

This commit is contained in:
leotyliu(刘天一) 2018-10-22 17:00:12 +08:00
parent 58e8ec469b
commit 09b6461396
2 changed files with 46 additions and 0 deletions

View 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)
}

View 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)
}