Skip to content

Commit 9672917

Browse files
Binary Search
1 parent 45ff9e1 commit 9672917

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

BinarySearch.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Binary search implementation in Go
3+
*/
4+
package main
5+
6+
func binarySearch(array []int, target int, lowIndex int, highIndex int) int {
7+
if highIndex < lowIndex {
8+
return -1
9+
}
10+
mid := int((lowIndex + highIndex) / 2)
11+
if array[mid] > target {
12+
return binarySearch(array, target, lowIndex, mid)
13+
} else if array[mid] < target {
14+
return binarySearch(array, target, mid+1, highIndex)
15+
} else {
16+
return mid
17+
}
18+
}
19+
20+
func iterBinarySearch(array []int, target int, lowIndex int, highIndex int) int {
21+
startIndex := lowIndex
22+
endIndex := highIndex
23+
var mid int
24+
for startIndex < endIndex {
25+
mid = int((startIndex + endIndex) / 2)
26+
if array[mid] > target {
27+
endIndex = mid
28+
} else if array[mid] < target {
29+
startIndex = mid
30+
} else {
31+
return mid
32+
}
33+
}
34+
return -1
35+
}

0 commit comments

Comments
 (0)