Learning GoLang: Binary Search Algorithm

in #programming5 years ago
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity.

Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Binary Search Algorithm Implementation in GoLang


Using GoLang to search a number in an array of sorted numbers using Binary Search. The time complexity is O(LogN).

func search(nums []int, target int) int {
    var i, j = 0, len(nums) - 1
    for i <= j {
        var mid = i + (j - i) / 2
        if nums[mid] == target {
            return mid
        }
        if target > nums[mid] {
            i = mid + 1
        } else {
            j = mid - 1
        }
    }    
    return -1
}

See other Binary Search algorithms:

Reposted from Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

  1. Voting Algorithm Updated to Favor those High Delegations!
  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.084
BTC 60423.20
ETH 1583.38
USDT 1.00
SBD 0.42