Go?語言sort?中的sortInts?方法
前言:
排序算法一直是很經(jīng)常使用的功能。Go 語言標(biāo)準(zhǔn)庫為我們提供了方便快捷的 ??sort?? 包 ,這個包實現(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()?? 指定的索引。
它接受兩個參數(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)文章
Golang新提案:panic?能不能加個?PanicError?
這篇文章主要為大家介紹了Golang的新提案關(guān)于panic能不能加個PanicError的問題分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12

