Skip to content

Commit

Permalink
fix: Update generics in counting sort (#676)
Browse files Browse the repository at this point in the history
Co-authored-by: Rak Laptudirm <[email protected]>
  • Loading branch information
Transmigration-zhou and raklaptudirm authored Oct 11, 2023
1 parent 85451af commit de90bd8
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions sort/countingsort.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,27 @@ package sort

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

func Count[T constraints.Number](data []int) []int {
var aMin, aMax = -1000, 1000
func Count[T constraints.Integer](data []T) []T {
if len(data) == 0 {
return data
}
var aMin, aMax = data[0], data[0]
for _, x := range data {
if x < aMin {
aMin = x
}
if x > aMax {
aMax = x
}
}
count := make([]int, aMax-aMin+1)
for _, x := range data {
count[x-aMin]++ // this is the reason for having only Number constraint instead of Ordered.
count[x-aMin]++ // this is the reason for having only Integer constraint instead of Ordered.
}
z := 0
for i, c := range count {
for c > 0 {
data[z] = i + aMin
data[z] = T(i) + aMin
z++
c--
}
Expand Down

0 comments on commit de90bd8

Please sign in to comment.