Skip to content

Commit 09b6461

Browse files
author
leotyliu(刘天一)
committed
14_sorts by golang
1 parent 58e8ec4 commit 09b6461

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

go/14_sorts/CountingSort.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package _4_sorts
2+
3+
import "math"
4+
5+
func CountingSort(a []int, n int) {
6+
if n <= 1 {
7+
return
8+
}
9+
10+
var max int = math.MinInt32
11+
for i := range a {
12+
if a[i] > max {
13+
max = a[i]
14+
}
15+
}
16+
17+
c := make([]int, max+1)
18+
for i := range a {
19+
c[a[i]]++
20+
}
21+
for i := 1; i <= max; i++ {
22+
c[i] += c[i-1]
23+
}
24+
25+
r := make([]int, n)
26+
for i := range a {
27+
index := c[a[i]] - 1
28+
r[index] = a[i]
29+
c[a[i]]--
30+
}
31+
32+
copy(a, r)
33+
}

go/14_sorts/CountingSort_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package _4_sorts
2+
3+
import "testing"
4+
5+
func TestCountingSort(t *testing.T) {
6+
arr := []int{5, 4}
7+
CountingSort(arr, len(arr))
8+
t.Log(arr)
9+
10+
arr = []int{5, 4, 3, 2, 1}
11+
CountingSort(arr, len(arr))
12+
t.Log(arr)
13+
}

0 commit comments

Comments
 (0)