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
package main

import (
"fmt"
)

func main() {
var lookingFor int = 6
var sortedArray []int = []int{1, 3, 4, 6, 7, 9, 10, 11, 13}
index := binarySearch(sortedArray, lookingFor)
fmt.Println("the array", sortedArray)
fmt.Println("the lookingFor", lookingFor)
if index >= 0 {
fmt.Println("Find the index:", index)
} else {
fmt.Println("Not Find the Data!")
}
}

func binarySearch(sortedArray []int, lookingFor int) int {
var low int = 0
var high int = len(sortedArray) - 1
for low <= high {
var mid int = low + (high-low)/2
var midValue int = sortedArray[mid]
if midValue == lookingFor {
return mid
} else if midValue > lookingFor {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}