Golang Program to Implement Binary Search Algorithm


In programming, to search for anything from an array, linked List, or any other data structures we have a few search algorithms, one of which is binary search. In binary search, the prerequisite is that the data should be sorted. In binary search, we follow the divide and conquer approach in which we divide the data by applying some conditions and then perform the operation on that data only. In this way, we reduce the time complexity.

For example, if we have an array of elements {20, 44, 45, 54, 67, 88, 91} and we want to find 44 then the binary search algorithm will find the element in the below way.

  • Find the middle element 54 and compare it with the element to search i.e. 44 as 54 is greater then we will not search on the right side and divide the array and go right.

  • Now the array is {20, 44, 45}, again we will compare with the middle element, and this time the middle element matches the element we are searching for.

Algorithm

Step 1: Import the required packages at the top using the import keyword.

Step 2: Then the main function will get run first.

  • First, we are declaring and initialize the array.

  • Call the binarySearch() function to search the element by passing the array, size, and element to search in the parameter.

  • In the end, print the result whether the element is present or not.

Step 3.1: in the binarySearch() function

  • In the first method, we are running a for loop over the array where we have two iterators left and right.

  • Inside the loop, we are finding the middle of the left and right and compare the element with the value at the index m. If the value matches then we are returning the index.

  • If the value, at index m, is greater than the value we are searching for then we assign m-1 to the iterator right.

  • If the value, at index m, is lesser than the value we are searching for then we assign m to the iterator left.

  • In the end, we are returning -1 if the element is not present.

Step 3.2: in the binarySearch() function

  • In the second method, the function is recursive.

  • The base condition is that if the left iterator is greater than equal to the right iterator then we are returning -1.

  • Inside the recursive function, we are finding the middle of the left and right and compare the element with the value at the index m. If the value matches then we are returning the index.

  • If the value, at index m, is greater than the value we are searching for then we are calling the binarySearch() function by passing m-1 to the iterator right.

  • If the value, at index m, is lesser than the value we are searching for then we are calling the binarySearch() function by passing m to the iterator left.

Example 1

In this example, we are going to implement binary search using a simple for loop. In the loop, we will find the middle element between the index right and left. If the element at index m matches with the element we are searching then we will return m and stop iterating else we will update right and left accordingly and keep iterating.

package main

import "fmt"

// function to print the array with array and
// size of the array as argument
func printArray(array []int, size int) {
    for i := 0; i < size; i++ {
        fmt.Print(array[i], " ")
    }
    fmt.Println()
}

// binary search function to find an element in the array
func binarySearch(array []int, size int, toFind int) int {
    var left, right, m int
    left = 0
    right = size

    for left < right {
        m = (right + left) / 2
        if array[m] == toFind {
            // if the element at index m is equal to the element we
            // are searching then returning m
            return m
        } else if array[m] > toFind {
            //If the element at index m is greater than the element
            //We are searching then we are skipping the right side
            // of the array
            right = m - 1
        } else {
            //If the element at index m is less than the element
            //We are searching then we are skipping the left side
            // of the array
            left = m
        }
    }

    return -1
}

func main() {
    // decalring and initializing the
    // array using the shorthand method
    array := []int{20, 44, 45, 54, 67, 88, 91}

    // decalring and initializing the
    // variable using the var keyword
    var toSearch int
    toSearch = 3

    fmt.Println("Golang program to find an element in an array using binary search using for loop.")
    fmt.Print("array: ")
    printArray(array, 6)
    // linear search function passing array and
    // variable as a parameter
    index := binarySearch(array, 6, toSearch)

    if index == -1 {
        fmt.Println(toSearch, "is not present in the array.")
    } else {
        fmt.Println(toSearch, "is present at index", index, "in the array.")
    }

}

Output 

Golang program to find an element in an array using binary search recursively.
array: 20 44 45 54 67 88 
3 is not present in the array.

Example 2

In this example, we are going to implement binary search using a recursive function. In the recursive call, we will find the middle element between the index right and left. If the element at index m matches with the element we are searching then we will return m and stop the recursive call else we will update right and left accordingly and keep calling the function until the base condition matches.

package main

import "fmt"

   // function to print the array with array and
   // size of the array as argument
   func printArray(array []int, size int) {
      for i := 0; i < size; i++ {
         fmt.Print(array[i], " ")
      }
      fmt.Println()
   }

   // binary search function to find an element in the array
   func binarySearch(array []int, left int, right int, toFind int) int {
      if left >= right {
         // returning -1 if value not present in the array
         return -1
      }
      //Finding a middle index of the current array
      m := (right + left) / 2

     if array[m] == toFind {
        // if the element at index m is equal to the element we
        // are searching then returning m
        return m
     } else if array[m] > toFind {
        //If the element at index m is greater than the element
        //We are searching then we are skipping the right side
        // of the array
        return binarySearch(array, left, m, toFind)
     } else {
        //If the element at index m is less than the element
        //We are searching then we are skipping the left side
        // of the array
        return binarySearch(array, m+1, right, toFind)
    }
}

func main() {
    // decalring and initializing the
    // array using the short hand method
    array := []int{20, 44, 45, 54, 67, 88, 91}

    // decalring and initializing the
    // variable using the var keyword
    var toSearch int
    toSearch = 44

    fmt.Println("Golang program to find an element in an array using binary search recursively.")
    fmt.Print("array: ")
    printArray(array, 6)
    // linear search function passing array and
    // variable as a parameter
    index := binarySearch(array, 0, 6, toSearch)

    if index == -1 {
        fmt.Println(toSearch, "is not present in the array.")
    } else {
        fmt.Println(toSearch, "is present at index", index, "in the array.")
    }

}

Output 

Golang program to find an element in an array using binary search using for loop.
array: 20 44 45 54 67 88 
44 is present at index 1 in the array.

Conclusion

These are the two ways to perform a binary search in Golang. The second method has multiple function calls and for the array with a large number of elements, the stack will get overloaded. Doing this for a simple operation is not an appropriate programming way so the method one of running for loop will be a more efficient way to achieve this. To learn more about Golang you can explore these tutorials.

Updated on: 10-Jul-2023

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements