March 2019
Intermediate to advanced
336 pages
9h 9m
English
The binary search algorithm compares the input value to the middle element of the sorted collection. If the values are not equal, the half in which the element is not found is eliminated. The search continues on the remaining half of the collection. The time complexity of this algorithm is in the order of O(log n).
The following code snippet shows an implementation of the binary search algorithm using the sort.Search function from the sort package. The main method initializes the elements array and invokes the sort.Search function to find an integer element:
//main package has examples shown// in Go Data Structures and algorithms bookpackage main// importing fmt packageimport ( "fmt" "sort")// main methodfunc main() { var elements ...Read now
Unlock full access