当前位置:网站首页>Go -- standard library sort package
Go -- standard library sort package
2022-06-30 10:21:00 【Fallacious】
sort There are many functions in the package , More commonly used are Sort function 、IsSorted function 、Slice function 、Search function .
To use sort Package functions , Need to achieve sort.Interface, Including the following 3 A way
type Interface interface {
Len() int // Returns the current number of elements
Less(i, j int) bool. // Judgment No. i The first element is less than the j Elements
Swap(i, j int) // Exchange two elements
}
sort The package has implemented several common base types (int,float,string and slice) Of sort.Interface The method in , We can use it directly .
1、Sort function
Sort The function is used to specify Interface Sort
Yes int Type array
func main() {
a := []int{
1, 2, 5, 3, 4}
sort.Ints(a)
fmt.Println(a)
}
Yes float64 Type slice
func main() {
a := []float64{
1, 2.9, 0.5, 3, 4}
sort.Float64s(a)
fmt.Println(a)
}
2、IsSorted function
IsSorted The function is used to determine whether it is ordered
Judge int Type of the array
func main() {
a := []int{
1, 2, 5, 3, 4}
fmt.Println(sort.IntsAreSorted(a))
sort.Ints(a)
fmt.Println(a)
fmt.Println(sort.IntsAreSorted(a))
}
3、Slice function
Slice The function is used to evaluate a Slice Sort , Function takes two parameters , The first one needs to be sorted Slice, The second is Slice Element comparison function . Two dimensional slices can be compared .
Sort by the first column
func main() {
interval := [][]int{
{
2,3},
{
1,3},
{
2,4},
{
2,2},
}
sort.Slice(interval, func(i, j int) bool {
return interval[i][0] < interval[j][0]
})
fmt.Println(interval)
}
The first column is the same , Sort by the second column
func main() {
interval := [][]int{
{
2,3},
{
1,3},
{
2,4},
{
2,2},
}
sort.Slice(interval, func(i, j int) bool {
if interval[i][0] == interval[j][0] {
return interval[i][1] < interval[j][1]
}else {
return interval[i][0] < interval[j][0]
}
})
fmt.Println(interval)
}
4、Search function
Used to binary find the position of the specified element .
lookup int The position of the specified element in the array
func main() {
a := []int{
1, 2, 5, 3, 4}
fmt.Println(sort.SearchInts(a,3))
sort.Ints(a)
fmt.Println(sort.SearchInts(a,3))
}
output:
2
2
As can be seen from the output , Whatever comes in a Is it orderly , All of them 3 stay Orderly a Position in .
5、 Other types
The above examples have been implemented by the government Len()、Less()、Swap() Methodical , If it is any other structure that we customize , We need to implement three methods before we can use sort Related functions in the package .
such as :
type Person struct {
Name string
Age int
}
type Persons []Person
func (p Persons) Len() int {
return len(p) }
func (p Persons) Less(i, j int) bool {
return p[i].Age < p[j].Age } // Sort by age
func (p Persons) Swap(i, j int) {
p[i], p[j] = p[j], p[i] }
func main() {
p1:=Person{
"a",3}
p2:=Person{
"b",7}
p3:=Person{
"c",5}
p :=Persons{
p1,p2,p3}
fmt.Println(p)
fmt.Println(sort.IsSorted(p)) // At this time, disorder , return false
sort.Sort(p)
fmt.Println(p)
fmt.Println(sort.IsSorted(p)) // It's in order , return true
}
边栏推荐
- NLopt--非线性优化--原理介绍及使用方法
- Theme Studio
- 2022 Season 6 perfect children's model toxon division finals came to a successful conclusion
- 著名画家史国良《丰收时节》数字藏品上线长城数艺
- Applying applet container technology to IOT ecological construction
- [C language quick start] let you know C language and get started with zero basics ③
- 背课文记单词,读课文记单词,读文章记单词;40篇文章搞定3500词;71篇文章突破中考单词;15篇文章贯通四级词汇;15篇文章贯通六级词汇
- GNN hands on practice (II): reproduction graph attention network gat
- 机器人系统动力学——惯性参数
- MySQL log management, backup and recovery of databases (2)
猜你喜欢
Robot system dynamics - inertia parameters
Rider does not prompt after opening unity script
力扣 428. 序列化和反序列化 N 叉树 DFS
Get through the supply chain Shenzhen gift show helps cross-border e-commerce find ways to break the situation
GNN动手实践(二):复现图注意力网络GAT
机械臂速成小指南(四):机械臂关键部件之减速机
“昆明城市咖啡地圖”活動再度開啟
MySQL index, transaction and storage engine of database (3)
South China Industrial Group launched digital economy and successfully held the city chain technology conference
Open source! Wenxin large model Ernie tiny lightweight technology, accurate and fast, full effect
随机推荐
Compare the maximum computing power of the Cenozoic top ant s19xp and the existing s19pro in bitland
[JVM] brief introduction to CMS
Robot system dynamics - inertia parameters
Xinguan has no lover, and all the people benefit from loving deeds to warm the world -- donation to the public welfare action of Shangqiu children's welfare home
1033 To Fill or Not to Fill
Right click to open CMD (command line)
Setting up the d2lbook environment for Li Mu's "hands on learning and deep learning"
Eth is not connected to the ore pool
Yixian e-commerce released its first quarterly report: adhere to R & D and brand investment to achieve sustainable and high-quality development
Node environment configuration
光明行动:共同呵护好孩子的眼睛——广西实施光明行动实地考察调研综述
逸仙电商发布一季报:坚持研发及品牌投入,实现可持续高质量发展
Installation and use
著名画家史国良《丰收时节》数字藏品上线长城数艺
Didn't receive robot state (joint angles) with recent timestamp within 1 seconds
打通供应链 深圳礼品展助跨境电商寻破局之道
Detailed explanation of commissioning methods and techniques
C语言实现扫雷游戏,附详解及完整代码
6.Redis新数据类型
[ark UI] implementation of the startup page of harmoniyos ETS