Go语言排序与接口实例分析
程序员文章站
2022-11-15 22:06:54
本文实例讲述了go语言排序与接口用法。分享给大家供大家参考。具体如下:
复制代码 代码如下:import "fmt"
type sorter interface {...
本文实例讲述了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语言程序设计有所帮助。
上一篇: 推特用户密码被明文泄漏