Sort排序|Golang|Sort包的使用|

Sort提供了三种排序方法。分别是直接调用、自定义结构排序、实现三个方法的排序

升序

import (
	"fmt"
	"sort"
)

func main() {
	numbers := []int{1, 6, 7, 3, 2, 8, 9, 4, 5}
	fmt.Println("排序前:", numbers)
	sort.Ints(numbers)    // 升序,就是从小到大
	fmt.Println("排序后:", numbers)
}

// output
排序前: [1 6 7 3 2 8 9 4 5]
排序后: [1 2 3 4 5 6 7 8 9]

降序

package main

import (
	"fmt"
	"sort"
)

func main() {
	numbers := []int{1, 6, 7, 3, 2, 8, 9, 4, 5}
	fmt.Println("排序前:", numbers)
	sort.Sort(sort.Reverse(sort.IntSlice(numbers))) // 降序,就是从大到小
	fmt.Println("排序后:", numbers)
}

// output
排序前: [1 6 7 3 2 8 9 4 5]
排序后: [9 8 7 6 5 4 3 2 1]

第二种:自定义结构的排序

package main

import (
	"fmt"
	"sort"
)

type User struct {
	name string
	age  int
}

func main() {
	users := []User{
		{name: "张三", age: 18},
		{"李四", 20},
		{"陈桂铭", 22},
	}
	sort.Slice(users, func(i, j int) bool {
		return users[i].age < users[j].age
	})
	fmt.Println(users)
}

// output
[{张三 18} {李四 20} {陈桂铭 22}]

第三种:针对sort包未提供的类型,如int32、float32等,需要实现接口Len()、Swap()、Less().

import (
	"fmt"
	"sort"
)

type Int32List []int32

func (s Int32List) Len() int {
	return len(s)
}
func (s Int32List) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s Int32List) Less(i, j int) bool {
	return s[i] < s[j]
}

func main() {
	k := []int32{3, 2, 7, 9, 5, 1, 0}
	sort.Sort(Int32List(k))
	fmt.Println(k) // 升序
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值