sort

Ints(arri)
对 int 类型的切片排序,  其中变量 arri 就是需要被升序排序的数组或切片
package main

import (
"fmt"
"sort"
)

func main() {
arr := []int{1, 5, 6, 2, 7, 3, 9, 9, 19, 4}
sort.Ints(arr)
fmt.Println(arr)
}

 

IntsAreSorted(a []int) bool

检查某个数组是否已经被排序

package main

import (
"fmt"
"sort"
)

func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 9, 9, 19}
fmt.Println(sort.IntsAreSorted(arr))
}

 

SearchInts(a []int, n int) int

在数组或切片中搜索一个元素,该数组或切片必须先被排序,返回对应结果的索引(当元素不存在时, 返回数组最后的索引位置)

package main

import (
"fmt"
"sort"
)

func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 9, 19}
index := sort.SearchInts(arr, 4)
fmt.Println(index)
}

 

Reverse(data Interface) Interface

Reverse实现对data的逆序排列

package main

import (
"fmt"
"sort"
)

func main() {
arr := []int{1, 5, 6, 2, 7, 3, 9, 9, 19, 4}
sort.Sort(sort.Reverse(sort.IntSlice(arr)))
fmt.Println(arr)
}

 

自定义排序, 只需实现以下三个函数:

Len() int

Less(i, j int) bool

Swap(i, j int)

package main

import (
    "fmt"
    "sort"
)

type MyInts []int

func (m MyInts) Len() int {
    return len(m)
}

func (m MyInts) Less(i, j int) bool {
    return m[i] < m[j]
}

func (m MyInts) Swap(i, j int) {
    m[i], m[j] = m[j], m[i]
}

func main() {
    m := MyInts{4, 6, 2, 7, 9, 3, 4, 7, 8}
    sort.Sort(m)
    fmt.Println(m)
}

 

 

————————————————
版权声明:本文为CSDN博主「msn217」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/chenbaoke/article/details/42340301

 

 

posted @ 2019-10-12 15:59  小帅哥一枚  阅读(182)  评论(0)    收藏  举报