Go language Sort package

Sort package


1. Common types are sorted

type Function
sort.Float64s([]float64) float64Sort slices in ascending order
sort.Float64sAreSorted([]float64)bool Determine float64whether the slice is in ascending order
sort.SearchFloat64s([]float64,float64)int Find the given value in the ascending slice , return the subscript if found, return the subscript suitable for inserting the value if not found
type Function
sort.Ints([]int) intSort slices in ascending order
sort.IntsAreSorted([]int)bool Determine intwhether the slice is in ascending order
sort.SearchInts([]int,int)int Find the given value in the ascending slice , return the subscript if found, return the subscript suitable for inserting the value if not found
type Function
sort.Strings([]string) Sort strings in ascending order
sort.StringsAreSorted([]string)bool Determine whether the string is in ascending order
sort.SearchStrings([]string,string)int Find the given value in the ascending slice , return the subscript if found, return the subscript suitable for inserting the value if not found

2. Custom sorting

type Function
sort.Slice([]Slice,func(i,j int)bool{}) Sort the specified slices according to the specified rules
sort.SliceSorted([]Slice,func(i,j int)bool{})bool Determine whether the specified slice has been sorted according to the specified rules
sort.SliceStable([]Slice,func(i,j int)bool{}) Sort the specified slices according to the specified rules, and keep the original relative position of equal elements
  • introduce
    • func(i,j int)boolThis belongs to the sorting rule : that is, what you write in the function
    • Example: Sort a member inside a structure
      insert image description here

3. Custom lookup

type Function
sort.Search(n int,f func(i int)bool)int Commonly used in an ordered, indexable, range is [0,n)the index of the lookup value in the data structure i(note nthe length of the slice)
Example: Find a first subscript value greater than v
insert image description here

4.Sort.Interface

  • The interface defined by sort requires the implementation Len()int(长度),Less(i,j int)bool(排序规则),Swap(i,j int)(交换)method
  • More flexible (write your own method)
type Function
sort.Sort(sort.interface) to sort
sort.Reverse(sort.Interface)sort.Interface reverse in sortsort.Sort(sort.Reverse(sort.interface))
sort.Stable(sort.interface) Sort, and preserve the original relative position for equal elements
sort.Float64Slice The data type defined by the sort package []float64implements the sort.interface interface
sort.IntSlice The sort package defines the data type and []intimplements sort.Interfacethe interface
sort.StringSlice The sort package defines the data type and []stringimplements sort.Interfacethe interface
These three types additionally provide Search(x)intand Sort()methods
insert image description here

Guess you like

Origin blog.csdn.net/JUIU9527/article/details/131684938