From 09b6461396359e579310fc1c470260efd436b62f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?leotyliu=28=E5=88=98=E5=A4=A9=E4=B8=80=29?= Date: Mon, 22 Oct 2018 17:00:12 +0800 Subject: [PATCH] 14_sorts by golang --- go/14_sorts/CountingSort.go | 33 ++++++++++++++++++++++++++++++++ go/14_sorts/CountingSort_test.go | 13 +++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 go/14_sorts/CountingSort.go create mode 100644 go/14_sorts/CountingSort_test.go diff --git a/go/14_sorts/CountingSort.go b/go/14_sorts/CountingSort.go new file mode 100644 index 0000000..834a2c1 --- /dev/null +++ b/go/14_sorts/CountingSort.go @@ -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) +} diff --git a/go/14_sorts/CountingSort_test.go b/go/14_sorts/CountingSort_test.go new file mode 100644 index 0000000..c6f5b46 --- /dev/null +++ b/go/14_sorts/CountingSort_test.go @@ -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) +}