参考博客:https://studygolang.com/articles/13173
基本类型排序
package main import ( "fmt" "sort" ) func main() { intList := []int{2, 4, 3, 5, 7, 6, 9, 8, 1, 0} floatList := []float64{4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14} stringList := []string{"a", "c", "b", "d", "f", "i", "z", "x", "w", "y"} sort.Sort(sort.IntSlice(intList)) sort.Sort(sort.Float64Slice(floatList)) sort.Sort(sort.StringSlice(stringList)) fmt.Printf("%v\n%v\n%v\n", intList, floatList, stringList) sort.Sort(sort.Reverse(sort.IntSlice(intList))) sort.Sort(sort.Reverse(sort.Float64Slice(floatList))) sort.Sort(sort.Reverse(sort.StringSlice(stringList))) fmt.Printf("%v\n%v\n%v\n", intList, floatList, stringList) }
结构体排序
package main import ( "fmt" "sort" ) type Person struct { Name string // 姓名 Age int // 年纪 } // 按照 Person.Age 从大到小排序 type PersonSlice []Person func (a PersonSlice) Len() int { // 重写 Len() 方法 return len(a) } func (a PersonSlice) Swap(i, j int) { // 重写 Swap() 方法 a[i], a[j] = a[j], a[i] } func (a PersonSlice) Less(i, j int) bool { // 重写 Less() 方法, 从小到大排序 return a[i].Age < a[j].Age } func main() { people := []Person{ {"zhang san", 12}, {"li si", 30}, {"wang wu", 52}, {"zhao liu", 26}, } fmt.Println(people) sort.Sort(PersonSlice(people)) // 按照 Age 的升序排序 fmt.Println(people) sort.Sort(sort.Reverse(PersonSlice(people))) // 按照 Age 的降序排序 fmt.Println(people) }
最小堆
heap是常用的实现优先队列的方法。heap包对任意实现了heap接口的类型提供堆操作。堆结构继承自sort.Interface, 而sort.Interface,需要实现三个方法:Len() int / Less(i, j int) bool / Swap(i, j int) 再加上堆接口定义的两个方法:Push(x interface{}) / Pop() interface{}。故只要实现了这五个方法,便定义了一个堆。
package main import ( "container/heap" "fmt" ) type IntHeap []int func (h IntHeap) Len() int { return len(h) } func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) } func (h *IntHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } func main() { h := &IntHeap{2, 1, 5, 100, 3, 6, 4, 5} heap.Init(h) heap.Push(h, 3) fmt.Printf("minimum: %d\n", (*h)[0]) for h.Len() > 0 { fmt.Printf("%d ", heap.Pop(h)) } }
package main import ( "container/heap" "fmt" ) type stu struct { name string age int } type Stu []stu func (t *Stu) Len() int { return len(*t) // } func (t *Stu) Less(i, j int) bool { return (*t)[i].age < (*t)[j].age } func (t *Stu) Swap(i, j int) { (*t)[i], (*t)[j] = (*t)[j], (*t)[i] } func (t *Stu) Push(x interface{}) { *t = append(*t, x.(stu)) } func (t *Stu) Pop() interface{} { n := len(*t) x := (*t)[n-1] *t = (*t)[:n-1] return x } func main() { student := &Stu{{"Amy", 21}, {"Dav", 15}, {"Spo", 22}, {"Reb", 11}} heap.Init(student) one := stu{"hund", 9} heap.Push(student, one) for student.Len() > 0 { fmt.Printf("%v\n", heap.Pop(student)) } }