Implement binary search
EasyGiven a sorted array of integers and a target value, write a function that returns the index of the target if it exists, or
-1 if it does not.For example, given the following inputs:
nums = [1, 3, 5, 7, 9, 11]target = 7
Your function should return
3 since the target 7 is at index 3.Binary search works by maintaining two pointers,
left and right, that define the search range. On each step, we check the middle element. If it matches the target, we return its index. If the target is smaller, we search the left half. If larger, we search the right half.Try it first
Solution
6 Essential Sorting & Searching Coding Interview Problems
Master Sorting & Searching by trying the coding challenges below.
- 1.Implement binary searchEasy
- 2.Merge intervalsMedium
- 3.Kth largest in arrayMedium
- 4.Intersection of ArraysMedium
- 5.Search sorted matrixHard
- 6.Search row & col sorted matrixHard
