Binary Search Example Using Golang

Binary Search Example Using Golang

This tutorial help to create a simple binary search in golang, binary search is very important to search technique to search element into array, Binary search is reduced to half at each step as an array is divided into two equal parts.

There are the 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 the 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 <= end {
                mid = (start + end) / 2
                if search_elem == a[mid] {
                        fmt.Printf("%d found at location %d.\n", search_elem, mid+1)
                        break
                } else if search_elem > a[mid] {
                        start = mid + 1
                } else if search_elem < a[mid] {
                        end = mid - 1
                }

        }

        if start > end {
                fmt.Printf("Not found! %d isn't present in the list.\n", search_elem)
        }
}