r/AskComputerScience • • May 24 '25
a better count sort ???
The first step in count sort is to count the frequencies of each integer. At this point why not just create a sorted array ?
Sample code in go:
random := make([]int, 20)
for i := range random {
random[i] = rand.Intn(5)
}
counts := make([]int, 5)
for _, num := range random {
counts[num]++
}
sorted := make([]int, 0, 20)
for i, count := range counts {
for j := 0; j < count; j++ {
sorted = append(sorted, i)
}
}
https://go.dev/play/p/-5z0QQRus5z
Wondering why count sort doesn't do this. What am I missing ?
1
Upvotes
View all comments
Show parent comment
1
u/[deleted] May 25 '25 edited May 25 '25
Good questions.
correct me if I'm wrong, but even if you do it like in CLRS you'd still need some other data structure. CLRS says:
wouldn't a hash table be one way of associating keys with satellite data ? or am I misinterpreting this ?
key maps to a linked list
yes, as objects are inserted in the linked list in the same order they are in the array