go語言排序查找sort包使用
sort包自帶基本類型排序函數
arr := []int{7,3,5,9,12}
sort.Ints(arr) //從小到大
sort.Sort(sort.Reverse(sort.IntSlice(arr))) //從大到小
arr2 := []float64{7,3,5,9,12}
sort.Float64s(arr2)
sort.Sort(sort.Reverse(sort.Float64Slice(arr2)))
arr3 := []string{"abbc", "a大賽", "dfgdf"}
sort.Strings(arr3)
sort.Sort(sort.Reverse(sort.StringSlice(arr3)))
結構體排序
所有的排序對象實作如下接口
type Interface interface {
// Len is the number of elements in the collection.
Len() int
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
Less(i, j int)方法中i是大下标元素,j就是小下标的元素,如果Less傳回true,進行元素交換
// Do ShellSort pass with gap 6
// It could be written in this simplified form cause b-a <= 12
for i := a + 6; i < b; i++ {
if data.Less(i, i-6) {
data.Swap(i, i-6)
}
}
切片結構體排序,添加Less函數。
//x必須是切片
func SliceStable(x interface{}, less func(i int, j int) bool)
people := []struct {
Name string
Age int
}
//...
//穩定排序
sort.SliceStable(people, func(i, j int) bool {
return people[i].Name < people[j].Name
})
//不穩定排序
sort.Slice(people, func(i, j int) bool {
return people[i].Name < people[j].Name
})
sort中的查找函數
//a是升序,二分查找,
func SearchInts(a []int, x int) int
func SearchStrings(a []string, x string) int
func SearchFloat64s(a []float64, x float64) int
a := []int{1, 2, 3, 4, 6, 7, 8}
x := 2
i := sort.SearchInts(a, x)
a := []float64{1.0, 2.0, 3.3, 4.6, 6.1, 7.2, 8.0}
x := 2.0
i := sort.SearchFloat64s(a, x)
//自定義判斷條件查找方法
func Search(n int, f func(int) bool) int
a := []int{1, 3, 6, 10, 15, 21, 28, 36, 45, 55}
x := 6
i := sort.Search(len(a), func(i int) bool {
return a[i] >= x
})
if i < len(a) && a[i] == x {
fmt.Printf("found %d at index %d in %v\n", x, i, a)
} else {
fmt.Printf("%d not found in %v\n", x, a)
}