NOTE

Binary Search

Use binary search to find a target value in a sorted ascending integer array.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Given an n-element sorted (ascending) integer array nums and a target value target, write a function to search for target in nums. If the target exists, return its index; otherwise return -1.

2. Approach

3. Implementation

func search(nums []int, target int) int {
    left := 0
    right := len(nums)-1
    for left <= right {
        mid := left+(right-left)/2
        if nums[mid] == target {
            return mid
        }else if nums[mid] < target {
            left = mid+1
        }else {
            right = mid -1
        }
    }
    return -1
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub