GO語言"sort"包中"Search"函數的用法及代碼示例。
用法:
func Search(n int, f func(int) bool) int
搜索使用二分搜索來查找並返回 [0, n) 中 f(i) 為真的最小索引 i,假設在 [0, n) 範圍內,f(i) == true 意味著 f(i+ 1) == 真。也就是說,搜索要求 f 對於輸入範圍 [0, n) 的某些(可能為空)前綴為假,然後對(可能為空)餘數為真;搜索返回第一個真正的索引。如果沒有這樣的索引,Search 返回 n。 (請注意,"not found" 返回值不是 -1,例如,strings.Index。)搜索僅對 [0, n) 範圍內的 i 調用 f(i)。
Search 的一個常見用途是在排序的、可索引的數據結構(例如數組或切片)中查找值 x 的索引 i。在這種情況下,參數 f(通常是閉包)捕獲要搜索的值,以及數據結構的索引和排序方式。
例如,給定一個按升序排序的切片數據,調用 Search(len(data), func(i int) bool { return data[i] >= 23 }) 返回最小索引 i 使得 data[i] > = 23。如果調用者要查找23是否在切片中,則必須單獨測試data[i] == 23。
搜索按降序排序的數據將使用 <= 運算符而不是 >= 運算符。
為了完成上麵的示例,以下代碼嘗試在按升序排序的整數切片數據中查找值 x:
x := 23
i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
if i < len(data) && data[i] == x {
// x is present at data[i]
} else {
// x is not present in data,
// but i is the index where it would be inserted.
}
作為一個更異想天開的例子,這個程序猜測你的號碼:
func GuessingGame() {
var s string
fmt.Printf("Pick an integer from 0 to 100.\n")
answer := sort.Search(100, func(i int) bool {
fmt.Printf("Is your number <= %d? ", i)
fmt.Scanf("%s", &s)
return s != "" && s[0] == 'y'
})
fmt.Printf("Your number is %d.\n", answer)
}
例子:
此示例演示如何搜索按升序排序的列表。
package main
import (
"fmt"
"sort"
)
func main() {
a := []int{1, 3, 6, 10, 15, 21, 28, 36, 45, 55}
x := 6
i := sort.Search(len(a), func(i int) bool { return a[i] >= x })
if i < len(a) && a[i] == x {
fmt.Printf("found %d at index %d in %v\n", x, i, a)
} else {
fmt.Printf("%d not found in %v\n", x, a)
}
}
輸出:
found 6 at index 2 in [1 3 6 10 15 21 28 36 45 55]
示例(降序):
此示例演示搜索按降序排序的列表。該方法與按升序搜索列表相同,但條件相反。
package main
import (
"fmt"
"sort"
)
func main() {
a := []int{55, 45, 36, 28, 21, 15, 10, 6, 3, 1}
x := 6
i := sort.Search(len(a), func(i int) bool { return a[i] <= x })
if i < len(a) && a[i] == x {
fmt.Printf("found %d at index %d in %v\n", x, i, a)
} else {
fmt.Printf("%d not found in %v\n", x, a)
}
}
輸出:
found 6 at index 7 in [55 45 36 28 21 15 10 6 3 1]
相關用法
- GO SearchFloat64s用法及代碼示例
- GO SearchInts用法及代碼示例
- GO Server.Shutdown用法及代碼示例
- GO SectionReader用法及代碼示例
- GO SendMail用法及代碼示例
- GO SectionReader.ReadAt用法及代碼示例
- GO ServeMux.Handle用法及代碼示例
- GO SectionReader.Size用法及代碼示例
- GO Server用法及代碼示例
- GO SectionReader.Seek用法及代碼示例
- GO SectionReader.Read用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO StreamWriter用法及代碼示例
- GO Split用法及代碼示例
- GO Slice用法及代碼示例
- GO StructTag.Lookup用法及代碼示例
- GO SplitAfter用法及代碼示例
- GO Sum256用法及代碼示例
- GO Sin用法及代碼示例
- GO Sprintf用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Search。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。