Skip to content

Commit de90bd8

Browse files
fix: Update generics in counting sort (TheAlgorithms#676)
Co-authored-by: Rak Laptudirm <[email protected]>
1 parent 85451af commit de90bd8

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

sort/countingsort.go

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,27 @@ package sort
88

99
import "github.com/TheAlgorithms/Go/constraints"
1010

11-
func Count[T constraints.Number](data []int) []int {
12-
var aMin, aMax = -1000, 1000
11+
func Count[T constraints.Integer](data []T) []T {
12+
if len(data) == 0 {
13+
return data
14+
}
15+
var aMin, aMax = data[0], data[0]
16+
for _, x := range data {
17+
if x < aMin {
18+
aMin = x
19+
}
20+
if x > aMax {
21+
aMax = x
22+
}
23+
}
1324
count := make([]int, aMax-aMin+1)
1425
for _, x := range data {
15-
count[x-aMin]++ // this is the reason for having only Number constraint instead of Ordered.
26+
count[x-aMin]++ // this is the reason for having only Integer constraint instead of Ordered.
1627
}
1728
z := 0
1829
for i, c := range count {
1930
for c > 0 {
20-
data[z] = i + aMin
31+
data[z] = T(i) + aMin
2132
z++
2233
c--
2334
}

0 commit comments

Comments
 (0)