Go语言排序和查找

排序操作主要都在 sort包中,导入就可以使用了,

import(“sort”)

sort.Ints对整数进行排序, sort.Strings对字符串进行排序, sort.Float64s对浮点数进行排序

package main

import (
  "fmt"
  "sort"
)

func testsort(){
  var st []int= []int{1,4,31,21,19,2}
  var sot []string = []string{"a","d","A","b"}
  sort.Ints(st)
  sort.Strings(sot)
  fmt.Println(st)
  fmt.Println(sot)
}
func main(){
  testsort()
}

结果:
[1 2 4 19 21 31]
[A a b d]

sort.SearchInts(a []int, b int) 从数组a中查找b,前提是a必须有序

sort.SearchFloats(a []float64, b float64) 从数组a中查找b,前提是a必须有序

sort.SearchStrings(a []string, b string) 从数组a中查找b,前提是a必须有序

package main

import (
  "fmt"
  "sort"
)
type stru struct {
  Name string
  age int
  score int
}
func teststruct(){
  s := stru{
    Name:"alex",
    age:18,
    score:100,
  }
  fmt.Printf("%p\n%p\n%p\n",&(s.Name),&(s.age),&(s.score))
}
func testsort(){
 var st []int= []int{1,4,31,21,19,2}
 var sot []string = []string{"a","d","A","b"}
 sort.Ints(st)
 sort.Strings(sot)
 index1 :=sort.SearchInts(st,4)
  fmt.Println(st)
 fmt.Println("index1 4的位置",index1)
 index2 :=sort.SearchStrings(sot,"d")
  fmt.Println(sot)
 fmt.Println("index2 d的位置",index2)

}
//func testsearch(a []int,b int){
//  sort.Search(a,b)
//}
func main(){
  testsort()
}

  

  

posted @ 2019-09-02 17:16  离人怎挽_wdj  阅读(184)  评论(0编辑  收藏  举报