-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
43 lines (35 loc) · 868 Bytes
/
main.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
package main
import "fmt"
// Returns the index of the target if found, otherwise -1.
func BinarySearch(arr []int, val int) int {
first, last := 0, len(arr)-1
// Check for first and last position
if len(arr) > 0 {
if arr[first] == val {
return first
} else if arr[last] == val {
return last
}
}
for first <= last {
mid := first + (last-first)/2
if arr[mid] == val {
return mid
} else if arr[mid] < val {
first = mid + 1
} else {
last = mid - 1
}
}
return -1
}
func main() {
arr := []int{1, 3, 5, 7, 9, 11, 13, 15}
val := 9
result := BinarySearch(arr, val)
if result != -1 {
fmt.Printf("Found %d at index %d\n", val, result)
} else {
fmt.Println("Target not found")
}
}