go语言排序查找sort包使用

go语言排序查找sort包使用

sort包自带基本类型排序函数
	arr := []int{7,3,5,9,12}
	sort.Ints(arr)	//从小到大
	sort.Sort(sort.Reverse(sort.IntSlice(arr)))	//从大到小

	arr2 := []float64{7,3,5,9,12}
	sort.Float64s(arr2)
	sort.Sort(sort.Reverse(sort.Float64Slice(arr2)))

	arr3 := []string{"abbc", "a大赛", "dfgdf"}
	sort.Strings(arr3)
	sort.Sort(sort.Reverse(sort.StringSlice(arr3)))
结构体排序

所有的排序对象实现如下接口

type Interface interface {
	// Len is the number of elements in the collection.
	Len() int
	Less(i, j int) bool
	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

Less(i, j int)方法中i是大下标元素,j就是小下标的元素,如果Less返回true,进行元素交换

// Do ShellSort pass with gap 6
// It could be written in this simplified form cause b-a <= 12
for i := a + 6; i < b; i++ {
	if data.Less(i, i-6) {
		data.Swap(i, i-6)
	}
}

切片结构体排序,添加Less函数。

//x必须是切片
func SliceStable(x interface{}, less func(i int, j int) bool)

people := []struct {
     Name string
     Age  int 
}
//...
//稳定排序
sort.SliceStable(people, func(i, j int) bool { 
	return people[i].Name < people[j].Name 
})
//不稳定排序
sort.Slice(people, func(i, j int) bool { 
	return people[i].Name < people[j].Name 
})
sort中的查找函数
//a是升序,二分查找,
func SearchInts(a []int, x int) int
func SearchStrings(a []string, x string) int
func SearchFloat64s(a []float64, x float64) int

a := []int{1, 2, 3, 4, 6, 7, 8}  
x := 2 
i := sort.SearchInts(a, x)

a := []float64{1.0, 2.0, 3.3, 4.6, 6.1, 7.2, 8.0}  
x := 2.0 
i := sort.SearchFloat64s(a, x)

//自定义判断条件查找方法
func Search(n int, f func(int) bool) int

a := []int{1, 3, 6, 10, 15, 21, 28, 36, 45, 55} 
x := 6  
i := sort.Search(len(a), func(i int) bool { 
	return a[i] >= x 
}) 
if i < len(a) && a[i] == x {     
	fmt.Printf("found %d at index %d in %v\n", x, i, a) 
} else {     
	fmt.Printf("%d not found in %v\n", x, a) 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值