Go?語言sort?中的sortInts?方法
前言:
排序算法一直是很經(jīng)常使用的功能。Go 語言標(biāo)準(zhǔn)庫為我們提供了方便快捷的 ??sort?? 包 ,這個(gè)包實(shí)現(xiàn)了四種基本排序算法:插入排序、歸并排序、堆排序和快速排序。
一、從有序數(shù)據(jù)中查找值
我們知道,常見查找算法有順序查找和二分查找。而二分查找就是基于有序數(shù)據(jù)的查找方法。而 Go 語言中的 ??sort?
? 包就提供了以下幾種查找的方法:
- SearchInts(slice ,val)
- SearchFloats(slice, val)
- SearchStrings(slice, val)
- Searh(count, testFunc)
二、SearchInts
??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]
到此這篇關(guān)于Go 語言sort 中的sortInts 方法的文章就介紹到這了,更多相關(guān)sortInts 方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go 1.22對net/http包的路由增強(qiáng)功能詳解
Go 1.22 版本對 net/http 包的路由功能進(jìn)行了增強(qiáng),引入了方法匹配(method matching)和通配符(wildcards)兩項(xiàng)新功能,本文將給大家詳細(xì)的介紹一下Go 1.22對net/http包的路由增強(qiáng)功能,需要的朋友可以參考下2024-02-02golang?gorm的Callbacks事務(wù)回滾對象操作示例
這篇文章主要為大家介紹了golang?gorm的Callbacks事務(wù)回滾對象操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-04-04Go語言基礎(chǔ)之網(wǎng)絡(luò)編程全面教程示例
這篇文章主要為大家介紹了Go語言基礎(chǔ)之網(wǎng)絡(luò)編程全面教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12基于go+vue實(shí)現(xiàn)的golang每日新聞數(shù)據(jù)瀏覽與檢索平臺(tái)(推薦)
gonews是基于 go+vue 實(shí)現(xiàn)的golang每日新聞瀏覽與檢索平臺(tái),本文通過實(shí)例代碼給大家講解,介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友參考下吧2018-01-01GoFrame?gredis緩存DoVar及Conn連接對象的自動(dòng)序列化
這篇文章主要為大家介紹了GoFrame?gredis干貨DoVar?Conn連接對象自動(dòng)序列化詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06