Binary search (LeetCode)

problem [https://leetcode.com/problems/binary-search/ 704. Binary search].

Problem description
Given a sorted (in ascending order) integer array  of   elements and a   value, write a function to search   in. If  exists, then return its index, otherwise return -1.

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

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


 * Note
 * 1) You may assume that all elements in   are unique.
 * 2)   will be in the range.
 * 3) The value of each element in   will be in the range.

Trivial cases

 * If the array is empty, then return -1.
 * If the array has only one element, then return 0 if that element is the target; otherwise return -1.

General approach

 * 1) Keep a   pointer and a   pointer.
 * 2) * Initialize  to 0, and   to.
 * 3) Find   using   to prevent overflow.
 * 4) Compare target and.
 * 5) * If  then return.
 * 6) * If  then.
 * 7) * Otherwise.
 * 8) Iterate until.
 * 9) If we end up with , this means that our search has failed. Return -1 in this case.

Time complexity
The time complexity is O(log n), since we are squeezing the search interval by one half each time, until the search interval only has a size of 1.

Space complexity

 * Stack
 * The space complexity on stack is obviously O(1), since we only used a fixed set of helper variables to reduce our search space and to find the result.


 * Heap
 * The space complexity on stack is O(1) because we did not allocate any new objects.

So the total space complexity is O(1).

Programming notes

 * Use  to prevent overflow.
 * Use  as the while-loop condition to cover the case of only one element in the array.