Binary Search

class Solution {
    public int search(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return -1;
    }
}

Note that for the primitive array, e.g., int a[3],

  1. the a is a const pointer to the first element in the array, which means a = b is not allow

  2. it's allocated in the stack, as opposed to const int b[] = new int[3]

  3. to free the memory of the array b, and the objects contained in b, delete [] b should be used

  4. note that in char name[] = "hello", the name is an array of 6 chars, including the \0 as the null terminator

Last updated

Was this helpful?