您好,登錄后才能下訂單哦!
這篇文章主要講解了“Go語言sort中的sortInts方法怎么用”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Go語言sort中的sortInts方法怎么用”吧!
我們知道,常見查找算法有順序查找和二分查找。而二分查找就是基于有序數(shù)據(jù)的查找方法。而 Go 語言中的 sort
包就提供了以下幾種查找的方法:
SearchInts(slice ,val)
SearchFloats(slice, val)
SearchStrings(slice, val)
Searh(count, testFunc)
SearchInts()
函數(shù)是 sort 包的內(nèi)置函數(shù),用于在排序的整數(shù)切片中搜索給定元素 x
,并返回 Search()
指定的索引。
它接受兩個(gè)參數(shù)(a []int, x int
):
a 是 int 類型的排序切片,
x 是要搜索的 int 類型元素,并返回Search()
指定的索引
注意:如果 x
不存在,可能是 len(a)
,SearchInts()
結(jié)果是插入元素 x
的索引。切片必須按升序排序。
語法結(jié)構(gòu)如下:
func SearchInts(a []int, x int) int
返回值: SearchInts()
函數(shù)的返回類型是 int,它返回 Search 指定的索引。
例子一:
package main import ( "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) }
運(yùn)行該代碼:
$ go run main.go
Ints: [2025 2019 2012 2002 2022]
Ints Sorted: [2002 2012 2019 2022 2025]
Index of 2022: 3
例子二:
package main import ( "fmt" "sort" ) func main() { a := []int{10, 20, 25, 27, 30} x := 25 i := sort.SearchInts(a, x) fmt.Printf("Element %d found at index %d in %v\n", x, i, a) x = 5 i = sort.SearchInts(a, x) fmt.Printf("Element %d not found, it can inserted at index %d in %v\n", x, i, a) x = 40 i = sort.SearchInts(a, x) fmt.Printf("Element %d not found, it can inserted at index %d in %v\n", x, i, a) }
運(yùn)行結(jié)果:
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]
感謝各位的閱讀,以上就是“Go語言sort中的sortInts方法怎么用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)Go語言sort中的sortInts方法怎么用這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。