本文實(shí)例講述了Go語(yǔ)言排序與接口用法。分享給大家供大家參考。具體如下:
復(fù)制代碼 代碼如下:
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)
}
希望本文所述對(duì)大家的Go語(yǔ)言程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- go語(yǔ)言實(shí)現(xiàn)接口查詢
- Go語(yǔ)言接口定義與用法示例
- go語(yǔ)言接口用法實(shí)例分析
- Go語(yǔ)言接口用法實(shí)例
- 一篇文章帶你玩轉(zhuǎn)go語(yǔ)言的接口