【go从零单排】sorting排序、Sorting by Functions排序方法-????代码

sorting排序

package main

//导入slices包,提供了对切片的操作函数,包括排序和检查排序状态
import (
	"fmt"
	"slices"
)

func main() {
	//创建字符串类型的切片strs并赋值
	strs := []string{"c", "a", "b"}
	//排序slice.Sort()
	slices.Sort(strs)
	fmt.Println("Strings:", strs)
	//创建一个int类型的切片并赋值
	ints := []int{7, 2, 4}
	//排序slice.Sort()
	slices.Sort(ints)
	fmt.Println("Ints:   ", ints)
	//	slices.IsSorted() 返回是否已排序,已排序true,未排序false
	s := slices.IsSorted(ints)
	fmt.Println("Sorted: ", s)
}

//输出
//Strings: [a b c]
//Ints:    [2 4 7]
//Sorted:  true

Sorting by Functions排序方法

package main

//导入cmp包用来比较值,导入slices操作切片
import (
	"cmp"
	"fmt"
	"slices"
)

func main() {
	//创建string类型的切片fruits
	fruits := []string{"peach", "banana", "kiwi"}
	//定义比较函数,输入两个string,输出一个int
	lenCmp := func(a, b string) int {
		//返回两个string的长度差
		return cmp.Compare(len(a), len(b))
	}
	//使用slices.SortFunc()排序,按照lenCmp排序
	slices.SortFunc(fruits, lenCmp)
	fmt.Println(fruits)
	//定义结构体Person
	type Person struct {
		name string
		age  int
	}
	//创建Person实例并赋值给people切片
	people := []Person{
		Person{name: "Jax", age: 37},
		Person{name: "TJ", age: 25},
		Person{name: "Alex", age: 72},
	}
	//对传入的people排序,按照age排序
	slices.SortFunc(people,
		func(a, b Person) int {
			//使用cmp.Compare比较两个Person对象的年龄
			return cmp.Compare(a.age, b.age)
		})
	fmt.Println(people)
}

//输出
//[kiwi peach banana]
//[{TJ 25} {Jax 37} {Alex 72}]

sort.Interface

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
    people := []Person{
        {"Alice", 30},
        {"Bob", 25},
        {"Charlie", 35},
    }

    sort.Sort(ByAge(people))
    fmt.Println(people) // 输出: [{Bob 25} {Alice 30} {Charlie 35}]
}
上一篇:HTML DOM 简介


下一篇:Golang | Leetcode Golang题解之第557题反转字符串中的单词III-题解: