Source file
src/sort/example_search_test.go
1
2
3
4
5 package sort_test
6
7 import (
8 "fmt"
9 "sort"
10 "strings"
11 )
12
13
14 func ExampleSearch() {
15 a := []int{1, 3, 6, 10, 15, 21, 28, 36, 45, 55}
16 x := 6
17
18 i := sort.Search(len(a), func(i int) bool { return a[i] >= x })
19 if i < len(a) && a[i] == x {
20 fmt.Printf("found %d at index %d in %v\n", x, i, a)
21 } else {
22 fmt.Printf("%d not found in %v\n", x, a)
23 }
24
25
26 }
27
28
29
30
31 func ExampleSearch_descendingOrder() {
32 a := []int{55, 45, 36, 28, 21, 15, 10, 6, 3, 1}
33 x := 6
34
35 i := sort.Search(len(a), func(i int) bool { return a[i] <= x })
36 if i < len(a) && a[i] == x {
37 fmt.Printf("found %d at index %d in %v\n", x, i, a)
38 } else {
39 fmt.Printf("%d not found in %v\n", x, a)
40 }
41
42
43 }
44
45
46 func ExampleFind() {
47 a := []string{"apple", "banana", "lemon", "mango", "pear", "strawberry"}
48
49 for _, x := range []string{"banana", "orange"} {
50 i, found := sort.Find(len(a), func(i int) int {
51 return strings.Compare(x, a[i])
52 })
53 if found {
54 fmt.Printf("found %s at index %d\n", x, i)
55 } else {
56 fmt.Printf("%s not found, would insert at %d\n", x, i)
57 }
58 }
59
60
61
62
63 }
64
65
66 func ExampleSearchFloat64s() {
67 a := []float64{1.0, 2.0, 3.3, 4.6, 6.1, 7.2, 8.0}
68
69 x := 2.0
70 i := sort.SearchFloat64s(a, x)
71 fmt.Printf("found %g at index %d in %v\n", x, i, a)
72
73 x = 0.5
74 i = sort.SearchFloat64s(a, x)
75 fmt.Printf("%g not found, can be inserted at index %d in %v\n", x, i, a)
76
77
78
79 }
80
81
82 func ExampleSearchInts() {
83 a := []int{1, 2, 3, 4, 6, 7, 8}
84
85 x := 2
86 i := sort.SearchInts(a, x)
87 fmt.Printf("found %d at index %d in %v\n", x, i, a)
88
89 x = 5
90 i = sort.SearchInts(a, x)
91 fmt.Printf("%d not found, can be inserted at index %d in %v\n", x, i, a)
92
93
94
95 }
96
View as plain text