1.排序与查找操作

排序操作在sort包中,sort.Ints对整数进行排序,sort.Strings对字符串进行排序,sort.Float64对浮点数进行排序

package main

import (
    "fmt"
    "sort"
)

func testIntSort() {
    var a = [...]int{1, 8, 38, 2, 348, 484}
    //数组是值类型,不能直接排序,必须转为切片
    sort.Ints(a[:])
    fmt.Println(a)
}
func testStrings() {
    var a = [...]string{"abc", "efg", "b", "A", "eeee"}
    //按照字母顺序排序,从小到大
    sort.Strings(a[:])
    fmt.Println(a)
}

func testFloat() {
    var a = [...]float64{2.3, 0.8, 28.2, 392342.2, 0, 6}
    //从小到大排序
    sort.Float64s(a[:])
    fmt.Println(a)
}
func testIntSearch() {
    var a = [...]int{1, 8, 38, 2, 348, 484}
    //数组是值类型,不能直接排序,必须转为切片
    sort.Ints(a[:])
    //SearchInts默认排序后的位置,一定要排序后在查找
    index:=sort.SearchInts(a[:],348)

    fmt.Println(index)
}

func main() {
    testIntSort()
    testStrings()
    testFloat()
    testIntSearch()
}

 

相关文章:

  • 2022-12-23
  • 2021-10-31
  • 2021-10-31
  • 2022-02-21
  • 2022-12-23
  • 2022-12-23
  • 2021-05-23
  • 2021-07-06
猜你喜欢
  • 2021-10-20
  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
  • 2021-11-07
  • 2021-08-13
相关资源
相似解决方案