Skip to content

Instantly share code, notes, and snippets.

@capoferro
Last active December 30, 2015 04:29
Show Gist options
  • Select an option

  • Save capoferro/7775900 to your computer and use it in GitHub Desktop.

Select an option

Save capoferro/7775900 to your computer and use it in GitHub Desktop.
Radix sort in Go
package main
import (
"fmt"
"strconv"
"strings"
)
type Bucket struct {
elements [10]*BucketElement
}
func (b *Bucket) Insert(str string, digitIndex int) {
digit, _ := strconv.ParseInt(strings.Split(str, "")[digitIndex], 10, 0)
strElement := &BucketElement{Val: str}
if b.elements[digit] == nil {
b.elements[digit] = strElement
} else {
current := b.elements[digit]
for current.Next != nil {
current = current.Next
}
current.Next = strElement
}
}
func (b *Bucket) Squash() (squashedBucket []string) {
b.Traverse(func(val string, newLine bool) {
squashedBucket = append(squashedBucket, val)
})
return
}
func (b *Bucket) Clear() {
b.elements = [10]*BucketElement{}
}
func (b *Bucket) Traverse(action func(val string, newLine bool)) {
var current *BucketElement
var newLine bool
for _, e := range b.elements {
current = e
newLine = true
for current != nil {
action(current.Val, newLine)
newLine = false
current = current.Next
}
}
}
func (b *Bucket) Print() {
b.Traverse(func(val string, newLine bool) {
if newLine { println("") }
fmt.Printf("%v ", val)
})
println("")
}
type BucketElement struct {
Val string
Next *BucketElement
}
func main() {
ints := [...]int{1,21,23,3,444,4,5555,5,66666,6}
var strings []string
bucket := new(Bucket)
fmt.Printf("%v\n", ints)
println("...Radix!...")
max := 0
for _, n := range ints {
if n > max { max = n }
}
digits := 0
for max > 0 {
max /= 10
digits++
}
for i := digits-1; i >= 0; i-- {
if len(strings) == 0 {
for _, n := range ints {
bucket.Insert(fmt.Sprintf(fmt.Sprintf("%%0%dd", digits), n), i)
}
} else {
for _, n := range strings {
bucket.Insert(n, i)
}
}
strings = bucket.Squash()
bucket.Clear()
}
for i, _ := range ints {
parsedInt, _ := strconv.ParseInt(strings[i], 10, 0)
ints[i] = int(parsedInt)
}
fmt.Printf("%v\n", ints)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment