-
Notifications
You must be signed in to change notification settings - Fork 153
/
14_sort_search_unsorted.go
68 lines (64 loc) · 1.39 KB
/
14_sort_search_unsorted.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"fmt"
"sort"
)
func main() {
{
ns := []int{1, 2, 0, -1, -2}
num := -1
// Binary search the smallest index at which the number is greater than the given one (== 10)
fmt.Println("IsSorted:", sort.IsSorted(sort.IntSlice(ns)))
idx := sort.Search(len(ns), func(i int) bool {
fmt.Println("searching", ns[i])
return ns[i] >= num
})
fmt.Println("Result:", ns[idx])
}
/*
IsSorted: false
searching 0
searching 2
searching 1
Result: 1
*/
println()
{
ns := []int{2, 100, 1, 20, 10, 50}
num := 5
// Binary search the smallest index at which the number is greater than the given one (== 10)
fmt.Println("IsSorted:", sort.IsSorted(sort.IntSlice(ns)))
idx := sort.Search(len(ns), func(i int) bool {
fmt.Println("searching", ns[i])
return ns[i] > num
})
fmt.Println("Result:", ns[idx])
}
/*
IsSorted: false
searching 20
searching 100
searching 2
Result: 100
*/
println()
{
ns := []int{2, 100, 1, 20, 10, 50}
sort.Ints(ns)
num := 5
// Binary search the smallest index at which the number is greater than the given one (== 10)
fmt.Println("IsSorted:", sort.IsSorted(sort.IntSlice(ns)))
idx := sort.Search(len(ns), func(i int) bool {
fmt.Println("searching", ns[i])
return ns[i] > num
})
fmt.Println("Result:", ns[idx])
}
/*
IsSorted: true
searching 20
searching 2
searching 10
Result: 10
*/
}