Skip to content

Commit d161fa3

Browse files
authored
Merge pull request deutranium#181 from codelixir/master
Implemented binary search in golang
2 parents 25dca37 + 59bed5f commit d161fa3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package main
2+
3+
import "fmt"
4+
5+
// recursive implementation of binary search
6+
func binarySearch(arr []int, x, l, r int) (int, bool) {
7+
8+
// boundary condition
9+
if l > r {
10+
return -1, false
11+
}
12+
13+
if mid := (r-l)/2 + l; arr[mid] == x { // when found, return the index
14+
return mid, true
15+
} else if arr[mid] < x { // if query element is greater than the middle, search the right half
16+
return binarySearch(arr, x, mid+1, r)
17+
} else { // if query element is less than the middle, search the left half
18+
return binarySearch(arr, x, l, mid-1)
19+
}
20+
}
21+
22+
func main() {
23+
fmt.Printf("Enter number of elements in array: ")
24+
var n, x int
25+
fmt.Scanf("%d", &n)
26+
27+
fmt.Printf("Enter the sorted array: ")
28+
var arr []int
29+
for i := 0; i < n; i++ {
30+
var k int
31+
fmt.Scanf("%d", &k)
32+
arr = append(arr, k)
33+
}
34+
35+
fmt.Printf("Enter the element to be searched: ")
36+
fmt.Scanf("%d", &x)
37+
38+
idx, found := binarySearch(arr, x, 0, n-1)
39+
40+
if !found {
41+
fmt.Printf("Element %d not found.\n", x)
42+
} else {
43+
fmt.Printf("Element %d found at position %d.\n", x, idx)
44+
}
45+
}

0 commit comments

Comments
 (0)