Go語言排序與接口實例分析
更新時間:2015年02月27日 15:04:30 作者:秋風秋雨
這篇文章主要介紹了Go語言排序與接口,實例分析了排序與接口的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Go語言排序與接口用法。分享給大家供大家參考。具體如下:
復制代碼 代碼如下:
import "fmt"
type Sorter interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
type Xi []int
type Xs []string
func (p Xi) Len() int { return len(p) }
func (p Xi) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xi) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func (p Xs) Len() int { return len(p) }
func (p Xs) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xs) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func Sort(x Sorter) {
for i := 0; i < x.Len() - 1; i++ {
for j := i + 1; j < x.Len(); j++ {
if x.Less(i, j) {
x.Swap(i, j)
}
}
}
}
func main() {
ints := Xi{44, 67, 3, 17, 89, 10, 73, 9, 14, 8}
strings := Xs{"nut", "ape", "elephant", "zoo", "go"}
Sort(ints)
fmt.Printf("%v\n", ints)
Sort(strings)
fmt.Printf("%v\n", strings)
}
type Sorter interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
type Xi []int
type Xs []string
func (p Xi) Len() int { return len(p) }
func (p Xi) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xi) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func (p Xs) Len() int { return len(p) }
func (p Xs) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xs) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func Sort(x Sorter) {
for i := 0; i < x.Len() - 1; i++ {
for j := i + 1; j < x.Len(); j++ {
if x.Less(i, j) {
x.Swap(i, j)
}
}
}
}
func main() {
ints := Xi{44, 67, 3, 17, 89, 10, 73, 9, 14, 8}
strings := Xs{"nut", "ape", "elephant", "zoo", "go"}
Sort(ints)
fmt.Printf("%v\n", ints)
Sort(strings)
fmt.Printf("%v\n", strings)
}
希望本文所述對大家的Go語言程序設計有所幫助。
相關文章
詳解如何在golang項目開發(fā)中創(chuàng)建自己的Module
既然我們使用了很多開源的 module為我們的日常開發(fā)提供了很多的便捷性,那我們該如何實現(xiàn)自己的 module 來提供給團隊中使用,接下小編就給大家介紹一下在golang項目開發(fā)如何創(chuàng)建自己的Module,需要的朋友可以參考下2023-09-09
Golang并發(fā)編程之main goroutine的創(chuàng)建與調度詳解
這篇文章主要為大家詳細介紹了Golang并發(fā)編程中main goroutine的創(chuàng)建與調度,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-03-03
使用Singleflight實現(xiàn)Golang代碼優(yōu)化
有許多方法可以優(yōu)化代碼以提高效率,減少運行進程就是其中之一,本文我們就來學習一下如何通過使用一個Go包Singleflight來減少重復進程,從而優(yōu)化Go代碼吧2023-09-09

