How to use sortInts method in Go language sort
This article mainly explains "how to use the sortInts method in the Go language sort". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use the sortInts method in the Go language sort".
First, find values from ordered data
We know that the common search algorithms are sequential search and binary search. Binary search is a search method based on ordered data. The sort package in the Go language provides the following ways to find it:
SearchInts (slice, val)
SearchFloats (slice, val)
SearchStrings (slice, val)
Searh (count, testFunc)
II. SearchInts
The SearchInts () function is a built-in function of the sort package that searches for a given element x in a sorted integer slice and returns the index specified by Search ().
It accepts two parameters (a [] int, x int):
An is a sorted slice of type int
X is the int type element to search for and returns the index specified by Search ()
Note: if x does not exist, it may be len (a), and the result of SearchInts () is the index of the inserted element x. Slices must be sorted in ascending order.
The grammatical structure is as follows:
Func SearchInts (a [] int, x int) int
Return value: the return type of the SearchInts () function is int, which returns the index specified by Search.
Third, give examples
Example 1:
Package mainimport ("fmt"sort") func main () {ints: = [] int {2025, 2019, 2012, 2002, 2022} sortInts: = make ([] int, len (ints) copy (sortInts, ints) sort.Ints (sortInts) fmt.Println ("Ints:", ints) fmt.Println ("Ints Sorted:", sortInts) indexOf2022: = sort.SearchInts (sortInts, 2022) fmt.Println ("Index of 2022:", indexOf2022)}
Run the code:
$go run main.go
Ints: [2025 2019 2012 2002 2022]
Ints Sorted: [2002 2012 2019 2022 2025]
Index of 2022: 3
Example 2:
Package mainimport ("fmt"sort") func main () {a: = [] int {10,20,25,27,30} x: = 25i: = sort.SearchInts (a, x) fmt.Printf ("Element% d found at index% d in% v\ n", x, I, a) x = 5i = sort.SearchInts (a, x) fmt.Printf ("Element% d not found, it can inserted at index% d in% v\ n", x, I, a) x = 40i = sort.SearchInts (a) X) fmt.Printf ("Element% d not found, it can inserted at index% d in% v\ n", x, I, a)}
Running result:
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]
Thank you for your reading, the above is the content of "how to use the sortInts method in the Go language sort". After the study of this article, I believe you have a deeper understanding of how to use the sortInts method in the Go language sort. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!