forked from VAR-solutions/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount-sort.go
More file actions
45 lines (36 loc) · 899 Bytes
/
count-sort.go
File metadata and controls
45 lines (36 loc) · 899 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"fmt"
"runtime"
"strings"
)
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
var aMin, aMax = -1000, 1000
func main() {
fmt.Println("before:", a)
countingSort(a, aMin, aMax)
fmt.Println("after: ", a)
}
func countingSort(a []int, aMin, aMax int) {
defer func() {
if x := recover(); x != nil {
if _, ok := x.(runtime.Error); ok &&
strings.HasSuffix(x.(error).Error(), "index out of range") {
fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax)
return
}
panic(x)
}
}()
count := make([]int, aMax-aMin+1)
for _, x := range a {
count[x-aMin]++
}
z := 0
for i, c := range count {
for ; c > 0; c-- {
a[z] = i + aMin
z++
}
}
}