Skip to content

Instantly share code, notes, and snippets.

@rphuber
Created April 13, 2024 12:36
Show Gist options
  • Save rphuber/8a0f14e6be5070de1fe3ee45cd8939e8 to your computer and use it in GitHub Desktop.
Save rphuber/8a0f14e6be5070de1fe3ee45cd8939e8 to your computer and use it in GitHub Desktop.
Implemtation of counting sort in go
func countingSort(slice []Customer) []Customer {
// slice `sortedSlice` is created to store the sorted values
sortedSlice := make([]Customer, len(slice))
// slice `countSlice` is created to store the count of each value (line 32).
countSlice := make([]int, len(slice))
// `countSlice` is populated by iterating over the input `slice` and incrementing the count of each `Customer`'s `numPurchases`
for _, customer := range slice {
countSlice[customer.numPurchases]++
}
// `countSlice` is then updated to show cumulative counts
// This will help in determining the correct position of each element in the sorted output.
for i := 1; i < len(countSlice); i++ {
countSlice[i] += countSlice[i-1]
}
// original `slice` is iterated in reverse order.
// For each `Customer`, its `numPurchases` is used to find the correct position in the `sortedSlice`
// the `Customer` is placed in the `sortedSlice`,
// and the count in `countSlice` is decremented
for i := len(slice) - 1; i >= 0; i-- {
index := countSlice[slice[i].numPurchases] - 1
sortedSlice[index] = slice[i]
countSlice[slice[i].numPurchases]--
}
// return the sorted slice
return sortedSlice
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment