go语言---sort()排序

切片排序 sort

go语言标准库sort只对int,string,float64进行了封装,自己可以参考对其他的类型封装
sortTest1中对比了封装前后的使用方法,可以点进源码看

package main

import (
	"fmt"
	"sort"
)

func main() {
	sortTest1()
	sortTest2()
	sortTest3()
}

func sortTest1() {
	num := [] int{3, 5, 2, 1, 6, 4}
	fmt.Println(num) // [3 5 2 1 6 4]
	sort.Ints(num)   // 封装后的简单用法
	fmt.Println(num) // [1 2 3 4 5 6]

	num2 := [] int{3, 2, 4, 1, 6, 5}
	fmt.Println(num2)              // [3 2 4 1 6 5]
	sort.Sort(sort.IntSlice(num2)) // 源码实现
	fmt.Println(num2)              // [1 2 3 4 5 6]

	// 降序排序,需要调用sort.Reverse(sort.IntSlice(int类型切片))
	num3 := []int{6, 3, 2, 8, 7}
	fmt.Println(num3) // [6 3 2 8 7]
	sort.Sort(sort.Reverse(sort.IntSlice(num3)))
	fmt.Println(num3) // [8 7 6 3 2]
}

func sortTest2() {
	// 字符串是按照首字母,首字母一样时往后对比,开头是汉字的排在后面
	letters := []string{"c", "e", "a", "d", "b"}
	fmt.Println(letters) // [c e a d b]
	sort.Strings(letters)
	fmt.Println(letters) // [a b c d e]

	// 同样,也可以自己调用封装之前的方法
	letters2 := []string{"d", "q", "n", "y", "b"}
	fmt.Println(letters2) // [d q n y b]
	sort.Sort(sort.StringSlice(letters2))
	fmt.Println(letters2) // [b d n q y]

	// 带有汉字的排序
	str := []string {"world", "a你好", "你好", "hello", "help", "世界"}
	sort.Sort(sort.StringSlice(str))
	fmt.Println(str)  // [a你好 hello help world 世界 你好]
}

func sortTest3()  {
	// sort.SearchStrings()  要求是一个已经升序排序的切片
	// 如果找不到,返回的是该字符串应该插入的位置
	str := []string {"world", "a你好", "你好", "hello", "help", "世界"}
	// 没有排序时
	idx := sort.SearchStrings(str, "你好")
	idx1 := sort.SearchStrings(str, "hello")
	fmt.Println(idx, idx1)  // 6  2

	// 升序排序时
	sort.Strings(str)
	idx2 := sort.SearchStrings(str, "你好")
	idx3 := sort.SearchStrings(str, "hello")
	fmt.Println(idx2, idx3)  // 5  1


}

发布了22 篇原创文章 · 获赞 1 · 访问量 1864

猜你喜欢

转载自blog.csdn.net/weixin_42677653/article/details/105130793