go语言-排序的使用

本文介绍常用类型的排序方法

主要内容

  1. 字符串切片、整型切片与浮点型切片的排序

  2. 逆序排序

  3. 自定义类型的排序

  4. 对已排序的切片使用sort.search()进行查找指定元素

字符串切片排序与逆序

Go 复制代码
	// 定义一个字符串切片
	strSlice := []string{"golang", "python", "C++", "C", "java", "typescript", "javascript"}
	// 方法一:使用sort包的Strings()函数对字符串切片进行排序
	sort.Strings(strSlice)
	fmt.Printf("排序后: %v\n", strSlice)

	// 方法二:使用sort.StringSlice类型,将原字符串切片放入sort.StringSlice类型切片中,再用sort.Sort()进行排序
	sss := sort.StringSlice{}
	for _, v := range strSlice {
		sss = append(sss, v)
	}
	sort.Sort(sss)
	fmt.Printf("排序后: %v\n", sss)

	// 对字符串逆序
	sort.Sort(sort.Reverse(sss))
	fmt.Printf("逆序排序后: %v\n", sss)

整型和浮点型切片排序

Go 复制代码
	// 定义一个整型切片
	intSlice := []int{2, 8, 4, 6, 3}

	// 使用sort.Ints()函数,直接对整型切片排序
	sort.Ints(intSlice)
	fmt.Printf("排序后: %v\n", intSlice)

	// 定义一个浮点数切片
	floatSlice := []float64{2.1, 8.1, 5.1, 4.1, 3.1}

	// 使用sort.Float64s()函数,直接对浮点数切片排序
	sort.Float64s(floatSlice)
	fmt.Printf("排序后: %v\n", floatSlice)

自定义类型的排序

Go 复制代码
// 定义一个student类型
type student struct {
	name  string
	age   int
	score int
}

// 定义一个切片类型
type studentGroupt []student


// 为了使用sort.Sort()接口对自定义类型进行排序,需要实现下面三方方法
func (s studentGroupt) Len() int { return len(s) }

func (s studentGroupt) Less(i, j int) bool {
	// 按分数排序从低到高排序
	return s[i].score < s[j].score

}

func (s studentGroupt) Swap(i, j int) { s[i], s[j] = s[j], s[i] }


func main(){

    sg := studentGroupt{student{
		name:  "xianwei",
		age:   39,
		score: 80,
	}, student{
		name:  "qiuyue",
		age:   36,
		score: 70,
	}, student{
		name:  "xianjun",
		age:   27,
		score: 100,
	}, student{
		name:  "xianjun2",
		age:   27,
		score: 98,
	}}

	sort.Sort(sg)
	fmt.Printf("排序后: %v\n", sg)
}

使用sort.search()进行查找

Search 常用于在一个已排序的,可索引的数据结构中寻找索引为 i 的值 x,例如数组或切片。这种情况下,实参 f,一般是一个闭包,会捕获所要搜索的值,以及索引并排序该数据结构的方式。

为了查找某个值,而不是某一范围的值时,如果slice以升序排序,则 f func中应该使用>=,如果slice以降序排序,则应该使用<=.

Go 复制代码
// 整型切片使用sort.Serarch()查找指定元素
    si := sort.IntSlice{2, 8, 4, 6, 3}

	sort.Sort(si)
	fmt.Printf("排序后:%v\n", si)

	target := 5
	index := sort.Search(len(si), func(i int) bool {
        // 找到后退出
		return si[i] >= target
	})

	if index < len(si) && target == si[index] {
		fmt.Println("found, index is ", index)
	} else {
		fmt.Println("not found")
	}



// 自定义类型切片使用sort.Serarch()查找指定元素

    sort.Sort(sg)
	fmt.Printf("排序后: %v\n", sg)

	target2 := student{
		name:  "qiuyue",
		age:   36,
		score: 70,
	}
	// 对自定义类型,按其余某个可比较的年龄字段来查找
	index2 := sort.Search(len(sg), func(i int) bool {
		return sg[i].age >= target2.age
	})
	if index2 < len(si) && target2.age == sg[index2].age {
		fmt.Println("found, index is ", index2)
	} else {
		fmt.Println("not found")
	}
相关推荐
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题1 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说1 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔1 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
绿箭柠檬茶1 天前
Ubuntu 服务器配置转发网络访问
服务器·网络·ubuntu
风_峰1 天前
Ubuntu Linux SD卡分区操作
嵌入式硬件·ubuntu·fpga开发
我是菜鸟0713号1 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_1 天前
QT(4)
开发语言·汇编·c++·qt·算法