Skip to content

Instantly share code, notes, and snippets.

@kellegous
Last active August 29, 2015 14:00
Show Gist options
  • Save kellegous/11328637 to your computer and use it in GitHub Desktop.
Save kellegous/11328637 to your computer and use it in GitHub Desktop.
Grew tired of creating new types to sort...
package util
import (
"sort"
)
type sorter struct {
n int
less func(i, j int) bool
swap func(i, j int)
}
func (s *sorter) Less(i, j int) bool {
return s.less(i, j)
}
func (s *sorter) Swap(i, j int) {
s.swap(i, j)
}
func (s *sorter) Len() int {
return s.n
}
func Sort(n int, less func(i, j int) bool, swap func(i, j int)) {
sort.Sort(&sorter{
n: n,
less: less,
swap: swap,
})
}
func SortIndex(n int, less func(i, j int) bool) []int {
idx := make([]int, n)
for i := 0; i < n; i++ {
idx[i] = i
}
sort.Sort(&sorter{
n: n,
less: func(i, j int) bool {
return less(idx[i], idx[j])
},
swap: func(i, j int) {
idx[i], idx[j] = idx[j], idx[i]
},
})
return idx
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment