Binary Search is a searching algorithm for finding an element’s position, if it exists, in a sorted array.
Implementation Python Go JavaScript C++ Java def search(nums, k): right = len(nums) left = 0 while left <= right: mid = (left + right) // 2 if nums[mid] == k: return mid elif nums[mid] > k: right = mid - 1 else: left = mid + 1 return -1 func search(nums []int, key int) int { left := 0; right := len(nums) var mid int for left <= right { mid = left + (right - left) / 2 if nums[mid] == key { return mid } if nums[mid] < key { left = mid + 1 } else { right = mid - 1 } } return -1 } function search(array, key) { let left = 0; let right = array.
Read more...