In the data structure there is a lot of space in the introduction of various sorting algorithms, so we can see the importance of sorting in daily development.

If you are interested in sorting algorithms, you can browse Python to see what sort algorithms you want to see implemented.

Instead of talking about how to implement various sorting algorithms with Go, we’ll talk about how sorting is designed in Go.

What sort types have been implemented in Go

  • sort.Ints

    Sort the int slices

  • sort.Float64s

    Sort the Float64 slices

  • sort.Strings

    Sort String slices

Positive sequence alignment

Sort.ints calls sort.sort for sorting, internally using a quicksort algorithm

sortInts := []int{2.3.4.1}
sort.Ints(sortInts)
log.Println(sortInts)

# out
[1.2.3.4]
Copy the code

trans

sortInts := []int{2.3.4.1}
sort.Sort(sort.Reverse(sort.IntSlice(sortInts)))
log.Println(sortInts)

# out
[4 3 2 1]
Copy the code

Determine if a set is ordered

isSort:=sort.IsSorted(sort.IntSlice([]int{1.2.3.4}))
log.Println(isSort)
/ / short
isSort=sort.IntsAreSorted([]int{1.2.3.4})
log.Println(isSort)

# out
true
true
Copy the code

A stable sort

Unlike sort.sort, sort.stable automatically selects a more appropriate sort based on the number of elements, internally using direct insert sort and merge sort

sortInts := []int{2.4.3.1}
sort.Stable(sort.IntSlice(sortInts))
log.Println(sortInts)
Copy the code

Search for ordered sets

Ordered sets must be arranged in ascending order

Search results for non-ordered collections do not return the correct index, so you should avoid searching for non-ordered collections.

sortInts := []int{1.2.3.4}
index:=sort.Se(sortInts,2)
log.Println(index)

# out
1
Copy the code

Custom sort

To simulate the descending order

sortInts := []int{1.5.8.10.4}
sort.Slice(sortInts, func(i, j int) bool {
        return sortInts[i]>sortInts[j]
})
log.Println(sortInts)
Copy the code

This function supports sorting complex types

people := []struct {
    Name string
    Age  int
}{
    {"Gopher".7},
    {"Alice".55},
    {"Vera".24},
    {"Bob".75},
}
sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
fmt.Println("By name:", people)
sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println("By age:", people)

# out
By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
Copy the code