Last active
August 29, 2015 14:00
-
-
Save kellegous/11328637 to your computer and use it in GitHub Desktop.
Grew tired of creating new types to sort...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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