Skip to content

Instantly share code, notes, and snippets.

@mikemadisonweb
Last active July 25, 2017 14:00
Show Gist options
  • Save mikemadisonweb/c8e182bfedc21c51eb83ed6d91671b15 to your computer and use it in GitHub Desktop.
Save mikemadisonweb/c8e182bfedc21c51eb83ed6d91671b15 to your computer and use it in GitHub Desktop.
Sort a slice or whatever with ability to provide sorting order (ascending/descending etc)
package main
import (
"fmt"
"sort"
)
/*
Use sort.Sort(data Interface).
Data is an object that is not necessarily a slice.
Data need to implement following functions.
http://golang-examples.tumblr.com/post/66101563407/sort-a-slice
*/
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
// If you want to sort []int, define a type intArray
type intArray []int
func (s intArray) Len() int { return len(s) }
func (s intArray) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s intArray) Less(i, j int) bool { return s[i] > s[j] }
func main() {
// and cast []int to intArray
a := []int{1, 43, 5, 10, 4}
sort.Sort(intArray(a))
fmt.Println(a)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment