Given an array of sorted integers in ascending order, and a target integer, write a function to search target in nums array. If target exists, return the index of the target in the array, otherwise return -1.
Try it yourself. The solutions are at the top of the page.
start = 0
and end = nums.length - 1
start <= end
condition.mid
which will be equal to let mid = Math.floor((start + end) / 2);
mid
is EQUAL to target, that means the target is found in the given array, return the current index
.mid
is GREATER than target, that means the target element must be present in the left part of the array, i.e. from start
to mid - 1
length.mid
is LESS than target, that means the target element must be present in the right part of the array, i.e. from mid + 1
to end.start = 0
and end = arr.length - 1
.binarySearchHelper()
that takes start
, end
, mid = start + end / 2
and nums
array.start > end
. that means the two pointers overlap.target === arr[mid]
- means we found the target, return mid element.arr[mid] < target
- recurse the binarySearchHelper()
method with start = mid + 1
condition, because if the target is present in the array, it will definitely be in the right sub array.arr[mid] > target
- recurse the binarySearchHelper()
method with end = mid - 1
condition, because if the target is present in the array, it will definitely be in the left sub array.