Now implement the classic binary search yourself from scratch. Given a sorted array and a target, return the index or -1.
Remember the three steps inside the loop:
mid = (left + right) // 2nums[mid] == target, return midnums[mid] < target, search right: left = mid + 1nums[mid] > target, search left: right = mid - 1Time: O(log n) — for 1 million elements, at most ~20 comparisons!
search([-1,0,3,5,9,12], 9)
4
search([-1,0,3,5,9,12], 2)
-1