Skip to content

sort

提示

[]int{5, 3, 1, 4, 2} 是slice,不是 array

array 不能够被 sort。sort 会改变原来的 slice!

Go 1.21

Go 1.21 加入泛型,所以 slices.Sort 可以自动处理 int、float、string 等类型。

go
slices.Sort(nums)

自定义排序

go
slices.SortFunc(users, func(a, b User) int {
	return a.Age - b.Age
})

int

go
nums := []int{5, 3, 1, 4, 2}
sort.Ints(nums)

fmt.Println(nums)
// [1 2 3 4 5]

float

go
	scores := []float64{3.2, 1.5, 9.8}
	sort.Float64s(scores)

	fmt.Println(scores)
	// [1.5 3.2 9.8]

string

go
names := []string{"bob", "alice", "tom"}
sort.Strings(names)

// [alice bob tom]

sort.Slice

go
type User struct {
	Name string
	Age  int
}

// to string
func (u User) String() string {
	return fmt.Sprintf("User(name=%s、age=%d)", u.Name, u.Age)
}

func main() {
	users := []User{
		{"Tom", 30},
		{"Alice", 20},
		{"Bob", 25},
	}

	sort.Slice(users, func(i, j int) bool {
		return users[i].Age < users[j].Age
	})

	fmt.Println(users)
	// [User(name=Alice、age=20) User(name=Bob、age=25) User(name=Tom、age=30)]

}

sort.Interface

go
type Interface interface {
    Len() int           // 返回元素数量
    Less(i, j int) bool // i < j 返回 true
    Swap(i, j int)      // 交换元素 i 和 j
}
go

type User struct {
    Name string
    Age  int
}

// UserSlice 实现 sort.Interface
type UserSlice []User

func (u UserSlice) Len() int {
    return len(u)
}

func (u UserSlice) Less(i, j int) bool {
    return u[i].Age < u[j].Age
}

func (u UserSlice) Swap(i, j int) {
    u[i], u[j] = u[j], u[i]
}

需要注意,实现 interface 的是 slice,而不是 struct

go
func main() {
    users := UserSlice{
        {"Alice", 30},
        {"Bob", 25},
        {"Charlie", 35},
    }

    sort.Sort(users)

    fmt.Println(users)
}

IntsAreSorted 判断是否已经排序过

go
sort.IntsAreSorted(nums)

土方法,挨个遍历

Binary Search / 二分查找

go
nums := []int{1,2,3,4,5}

index := sort.SearchInts(nums, 3)

fmt.Println(index)
// 2