Binary search in Go

Here is an example implementation of binary search in Go:

package main
import (
    "fmt"
)
// binarySearch searches for a given target element in the sorted input slice
func binarySearch(input []int, target int) int {
    left := 0
    right := len(input) - 1

    for left <= right {
        mid := (left + right) / 2

        if input[mid] == target {
            return mid
        } else if input[mid] < target {
            left = mid + 1
        } else {
            right = mid - 1
        }
    }

    return -1 // target not found
}

func main() {
    input := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    target := 7

    index := binarySearch(input, target)
    if index == -1 {
        fmt.Println("Target not found")
    } else {
        fmt.Printf("Target found at index %d\n", index)
    }
}

In this implementation, binarySearch() function takes two arguments, a sorted integer slice input, and a target element to search for. It then performs the binary search algorithm on the slice to find the index of the target element. If the target is found, it returns its index, otherwise it returns -1. In the main() function, we create an example slice and call the binarySearch() function to search for the target element.

You may also like...

Leave a Reply