binary search

    0

    1

    huxulm

    The binary_search function is designed to find an item in a sorted set. The function first calculates the left and right bounds of the search area. It then iterates through the set, comparing the item at the left bounds to the desired item at the right bounds. If the items are equal, the function returns the locality of the item at the midpoint between the left and right bounds. If the items are not equal, the function returns the size of the set (in terms of element numbers) after the addition of the item at the midpoint to the set.

    func binary_search(a []int, t int) int {
      n := len(a)
      lo, hi = 0, n
      for lo < hi {
        mid := (lo+hi)/2
        if a[mid] == t {
          return mid
        } else if a[mid] < t {
          lo = mid + 1
        } else {
          hi = mid
        }
      }
      return -1
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.