-
Notifications
You must be signed in to change notification settings - Fork 108
/
CountingSort.go
55 lines (49 loc) · 1.25 KB
/
CountingSort.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
package main
import "fmt"
const MaxUint = ^uint(0)
const MaxInt = int(MaxUint >> 1)
const MinInt = - MaxInt - 1
func countingSort(list []int) {
maxNumber := MinInt
minNumber := MaxInt
for _, v := range list {
if v > maxNumber {
maxNumber = v
}
if v < minNumber {
minNumber = v
}
}
count := make([]int, maxNumber - minNumber + 1)
for _, x := range list {
count[x - minNumber]++
}
index := 0
for i, c := range count {
for ; c > 0; c-- {
list[index] = i + minNumber
index++
}
}
}
func main() {
var x int
fmt.Printf("Enter the size of the array : ")
fmt.Scan(&x)
fmt.Printf("Enter the elements of the array : ")
a := make([]int, x)
for i := 0; i < x; i++ {
fmt.Scan(&a[i])
}
list := a // A copy of the array 'a' is assigned to 'list'
fmt.Println("before sorting", list)
countingSort(list)
fmt.Println("after sorting", list)
}
/*
Sample Input :
Enter the size of the array : 4
Enter the elements of the array : 12 29 10 78
Sample Output :
After sorting [10 12 29 78]
*/