Skip to content

Instantly share code, notes, and snippets.

@mushfiq
Created December 30, 2016 00:13
Show Gist options
  • Save mushfiq/7124531aa3331397292690bee4b53cb4 to your computer and use it in GitHub Desktop.
Save mushfiq/7124531aa3331397292690bee4b53cb4 to your computer and use it in GitHub Desktop.
Binary search implementation using golang.
package main
import "fmt"
func elementExists(input_array []int, max_index int, min_index int, element int) bool {
middle_index := (min_index + max_index) / 2
found := false
if min_index > max_index {
return false
}
if element == input_array[middle_index] {
found = true
} else if element < input_array[middle_index] {
max_index := middle_index - 1
return elementExists(input_array, max_index, min_index, element)
} else if element > input_array[middle_index] {
min_index := middle_index + 1
return elementExists(input_array, max_index, min_index, element)
}
return found
}
func main() {
input_array := []int{5, 9, 12, 14, 16, 17, 98, 100, 101, 123, 900}
element := 10000
min_index := 0
max_index := len(input_array) - 1
found_it := elementExists(input_array, max_index, min_index, element)
fmt.Println(found_it)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment