-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBinarysearch.go
More file actions
35 lines (33 loc) · 767 Bytes
/
Binarysearch.go
File metadata and controls
35 lines (33 loc) · 767 Bytes
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
/*
Binary search implementation in Go
*/
package main
func binarySearch(array []int, target int, lowIndex int, highIndex int) int {
if highIndex < lowIndex {
return -1
}
mid := int((lowIndex + highIndex) / 2)
if array[mid] > target {
return binarySearch(array, target, lowIndex, mid)
} else if array[mid] < target {
return binarySearch(array, target, mid+1, highIndex)
} else {
return mid
}
}
func iterBinarySearch(array []int, target int, lowIndex int, highIndex int) int {
startIndex := lowIndex
endIndex := highIndex
var mid int
for startIndex < endIndex {
mid = int((startIndex + endIndex) / 2)
if array[mid] > target {
endIndex = mid
} else if array[mid] < target {
startIndex = mid
} else {
return mid
}
}
return -1
}