Search⌘ K
AI Features

Solution Review: Binary Search

Learn how to implement and understand binary search in Go for sorted arrays. Discover how the algorithm divides search space effectively, compare elements, and analyze time complexity for efficient searching.

Solution

  • We can use binary search to search effectively when we have data arranged in increasing or decreasing order. We divide our search space in half at each stage.
  • We compare the middle value with
...
Go (1.6.2)
package main
import "fmt"
func BinarySearch(data []int, value int) bool {
var mid int
low := 0
high := len(data) - 1
for low <= high {
mid = (low + high)/2
if data[mid] == value { // values find
return true
} else {
if data[mid] < value { // move to left
low = mid + 1
} else {
high = mid - 1 // move to right
}
}
}
return false // value not found
}
//Testing code
func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 9}
fmt.Println("BinarySearch:", BinarySearch(arr, 8))
fmt.Println("BinarySearch:", BinarySearch(arr, 3))
}

Time complexity

Recurrence Relation: T(n)=T(n/2)+ ...