Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix. Update generics in counting sort #676

Merged
merged 2 commits into from
Oct 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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