Learning GoLang: Binary Search Algorithm
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 4Example 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
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- 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