-
Notifications
You must be signed in to change notification settings - Fork 1
/
counting_sort.go
67 lines (53 loc) · 1.03 KB
/
counting_sort.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"bufio"
"fmt"
"os"
)
func countingSort(arr []int, maxValue int) []int {
count := make([]int, maxValue)
for _, n := range arr {
count[n]++
}
for i := 1; i < len(count); i++ {
count[i] += count[i-1]
}
sorted := make([]int, len(arr))
for _, n := range arr {
sorted[count[n]-1] = n
count[n]--
}
return sorted
}
func main() {
stdin, err := os.Open(os.Getenv("INPUT_PATH"))
if err != nil {
stdin = os.Stdin
}
defer stdin.Close()
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
if err != nil {
stdout = os.Stdout
}
defer stdout.Close()
reader := bufio.NewReaderSize(stdin, 1024*1024)
writer := bufio.NewWriterSize(stdout, 1024*1024)
var n int
_, err = fmt.Fscanln(reader, &n)
checkError(err)
arr := make([]int, n)
for i := 0; i < n; i++ {
_, err = fmt.Fscan(reader, &arr[i])
checkError(err)
}
result := countingSort(arr, 11)
for _, counter := range result {
fmt.Fprintf(writer, "%d ", counter)
}
writer.Flush()
}
func checkError(err error) {
if err != nil {
panic(err)
}
}