Preface:
Sorting algorithms have always been a very common feature. The Go language standard library provides us with a convenient and fast sort package, which implements four types.Basic sorting algorithm:Insert sort, merge sort, heap sort, and quick sort.
1. Find values from ordered data
We know that common search algorithms have sequential search and binary search. Binary search is a search method based on ordered data. And the Go languagesort
The package is providedThe following search methods:
- SearchInts(slice ,val)
- SearchFloats(slice, val)
- SearchStrings(slice, val)
- Searh(count, testFunc)
2. SearchInts
SearchInts()
Functions are built-in functions of sort packages for searching for a given element in sorted integer slices x
, and returnSearch()
Specified index.
It accepts two parameters (a []int, x int
):
- a is a sorted slice of type int,
- x is the int type element to be searched for and returns
Search()
Specified index
Note: Ifx
Does not exist, it may belen(a)
,SearchInts()
The result is an insert elementx
index of . The slices must be sorted in ascending order.
The syntax structure is as follows:
func SearchInts(a []int, x int) int
Return value: SearchInts()
The return type of the function is int, which returns the index specified by Search.
3. Give an example
Example 1:
package main import ( "fmt" "sort" ) func main() { ints := []int{2025, 2019, 2012, 2002, 2022} sortInts := make([]int, len(ints)) copy(sortInts, ints) (sortInts) ("Ints: ", ints) ("Ints Sorted: ", sortInts) indexOf2022 := (sortInts, 2022) ("Index of 2022: ", indexOf2022) }
Run the code:
$ go run
Ints: [2025 2019 2012 2002 2022]
Ints Sorted: [2002 2012 2019 2022 2025]
Index of 2022: 3
Example 2:
package main import ( "fmt" "sort" ) func main() { a := []int{10, 20, 25, 27, 30} x := 25 i := (a, x) ("Element %d found at index %d in %v\n", x, i, a) x = 5 i = (a, x) ("Element %d not found, it can inserted at index %d in %v\n", x, i, a) x = 40 i = (a, x) ("Element %d not found, it can inserted at index %d in %v\n", x, i, a) }
Running results:
Element 25 found at index 2 in [10 20 25 27 30]
Element 5 not found, it can inserted at index 0 in [10 20 25 27 30]
Element 40 not found, it can inserted at index 5 in [10 20 25 27 30]
This is the article about the sortInts method in Go language sort. For more related sortInts method content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!