Skip to content

Commit

Permalink
14_sorts by golang
Browse files Browse the repository at this point in the history
  • Loading branch information
leotyliu(刘天一) committed Oct 22, 2018
1 parent 58e8ec4 commit 09b6461
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
33 changes: 33 additions & 0 deletions go/14_sorts/CountingSort.go
Original file line number Diff line number Diff line change
@@ -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 changes: 13 additions & 0 deletions go/14_sorts/CountingSort_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 09b6461

Please sign in to comment.