March 2020
Intermediate to advanced
406 pages
8h 39m
English
Binary search is an algorithm that is used to find the location of a specific element in a sorted array. It starts by targeting the middle element in the array. If there is no match, the algorithm next takes the half of the array that could contain the item and uses the middle value to find the target. As we learned in Chapter 2, Data Structures and Algorithms, binary search is an efficient algorithm at O (log n). The Go standard library sort package has a built-in binary search function. We can use it like so:
package mainimport ( "fmt" "sort")func main() { data := []int{1, 2, 3, 4, 5, 6} findInt := 2 out := sort.Search(len(data), func(i int) bool { return data[i] >= findInt }) fmt.Printf("Integer %d was found in %d at position ...Read now
Unlock full access