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

7 comments sorted by

View all comments

Show parent comment

1

u/[deleted] May 25 '25 edited May 25 '25

You’re making copies of the keys on which the sorting takes place, and all other data is lost.

good point.

that's what I got wrong. looks like in go this is done as shown in this post: https://stackoverflow.com/a/42872183/13815871