golang学习笔记系列之sort包的学习

sort

sort包提供了排序切片和用户自定义数据集以及相关功能的函数。

sort包主要针对[]int,[]float64,[]string以及其他自定义的切片排序,对于任何类型的切片,只要实现了LenLessSwap接口就可以对其进行排序。

sort.Sort默认使用快速排序方法,因此平均时间复杂度为nlog(n)

// Sort sorts data in ascending order as determined by the Less method.
// It makes one call to data.Len to determine n and O(n*log(n)) calls to
// data.Less and data.Swap. The sort is not guaranteed to be stable.
func Sort(data Interface) {
	n := data.Len()
	quickSort(data, 0, n, maxDepth(n))
}
package main

import (
   "fmt"
   "sort"
)

type Person struct {
   name   string
   age    int
   weight float64
}

type PersonSlice []Person

//实现Len方法,返回切片的长度
func (ps PersonSlice) Len() int {
   return len(ps)
}

//实现Less方法,定义比较规则
func (ps PersonSlice) Less(i int, j int) bool {
   return ps[i].age < ps[j].age //按照年龄进行比较
}

//实现Swap方法,定义交换规则
func (ps PersonSlice) Swap(i int, j int) {
   ps[i], ps[j] = ps[j], ps[i]
}

func main() {

   //对int切片进行排序 []float64和[]string的使用方法同此
   var a []int
   a = []int{5, 1, 3, 2, 4}
   fmt.Printf("排序前:a: %v\n", a)
   sort.Ints(a)
   fmt.Printf("排序后:a: %v\n", a)
   fmt.Printf("sort.IntsAreSorted(a): %v\n", sort.IntsAreSorted(a)) //判断[]int序列是不是增序序列
   fmt.Printf("sort.SearchInts(a, 3): %v\n", sort.SearchInts(a, 3)) //查找某一个元素的位置 默认是二分法进行查找

   //对自定义数据类型的切片进行排序
   tom := Person{name: "Tom", age: 18, weight: 66.7}
   jerry := Person{name: "Jerry", age: 16, weight: 56.7}
   jack := Person{name: "Jack", age: 19, weight: 78.1}
   hank := Person{name: "Hank", age: 18, weight: 61.7}
   marry := Person{name: "Marry", age: 20, weight: 55.7}
   var ps PersonSlice
   ps = append(ps, tom, jerry, jack, hank, marry)
   fmt.Printf("排序前ps: %v\n", ps)

   sort.Sort(ps)
   fmt.Printf("排序后ps: %v\n", ps) //按年龄是增序序列

}

运行结果

排序前:a: [5 1 3 2 4]
排序后:a: [1 2 3 4 5]
sort.IntsAreSorted(a): true
sort.SearchInts(a, 3): 2
排序前ps: [{Tom 18 66.7} {Jerry 16 56.7} {Jack 19 78.1} {Hank 18 61.7} {Marry 20 55.7}]
排序后ps: [{Jerry 16 56.7} {Tom 18 66.7} {Hank 18 61.7} {Jack 19 78.1} {Marry 20 55.7}]

同时更新于个人博客系统:golang学习笔记系列之sort包的学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值