Created
April 4, 2013 04:56
-
-
Save atomaths/5307931 to your computer and use it in GitHub Desktop.
Sort example in Go
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 main | |
import ( | |
"fmt" | |
"sort" | |
) | |
type Student struct { | |
Name string | |
Height, Weight int | |
} | |
type Students []*Student | |
func (s Students) Len() int { return len(s) } | |
func (s Students) Swap(i, j int) { s[i], s[j] = s[j], s[i] } | |
type ByName struct{ Students } | |
func (s ByName) Less(i, j int) bool { return s.Students[i].Name < s.Students[j].Name } | |
type ByHeight struct{ Students } | |
func (s ByHeight) Less(i, j int) bool { return s.Students[i].Height < s.Students[j].Height } | |
type ByWeight struct{ Students } | |
func (s ByWeight) Less(i, j int) bool { return s.Students[i].Weight < s.Students[j].Weight } | |
func printStudents(s []*Student) { | |
for _, o := range s { | |
fmt.Printf("%v: %v\t%v\n", o.Name, o.Height, o.Weight) | |
} | |
} | |
func main() { | |
s := []*Student{ | |
{"홍길동", 180, 77}, | |
{"김연아", 174, 76}, | |
{"류현진", 188, 82}, | |
{"김또깡", 182, 79}, | |
{"강호동", 188, 90}, | |
{"박소진", 165, 49}, | |
} | |
sort.Sort(ByName{s}) | |
fmt.Println("Students by Name:") | |
printStudents(s) | |
println() | |
sort.Sort(ByHeight{s}) | |
fmt.Println("Students by Height:") | |
printStudents(s) | |
println() | |
sort.Sort(ByWeight{s}) | |
fmt.Println("Students by Weight:") | |
printStudents(s) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment