This tutorial help to create simple Binary Search in golang, binary search is very important search technique to search element into array, Binary search reduced to half at each step as array is divided into two equal parts.
There are following rules for binary searching:
- The Binary search input array must be sorted.
- The Find mid index of the array.
- The middle element is greater than the element to be searched, then search the element in left portion of the array.The start index is (mid -1).
- The middle element is less than the element to be searched, then search the element in right portion of the array.The end index is (mid+1)
Golang Code For Binary Search
package main import ( "fmt" _ "os" ) func main() { a := []int{6, 8, 31, 54, 67, 71, 84, 95} fmt.Printf("%v", a) fmt.Println("\nPlease enter search value?") var search_elem int fmt.Scanf("%d", &search_elem) fmt.Println("Read number", search_elem, "from stdin") var mid int start := 0 len_arr := len(a) - 1 end := len_arr for start a[mid] { start = mid + 1 } else if search_elem end { fmt.Printf("Not found! %d isn't present in the list.\n", search_elem) } }
The post Binary Search Example Using Golang appeared first on Rest Api Example.