Implement Binary Search on a Sorted Array
Given a sorted array of integers, return the index of the given value.
We'll cover the following...
Statement
Binary search is an efficient algorithm used to find the position of a target value within a sorted array. It repeatedly divides the array in half, comparing the middle element with the target. Depending on the comparison, it narrows the search to the left or right half of the array, until the target is found or the subarray size becomes zero.
Given an array of integers, nums, sorted in ascending order, and an integer value, target. If the target exists in the array, return its index; otherwise, return -1.
Example
Given the following sorted array, if the target’s value is 9, the binary search returns 2.
Sample input
nums = [1, 3, 9, 10, 12]
target = 9
Expected output
2
Try it yourself
Solution 1: Iterative
In the iterative approach, here is how the algorithm works:
- At each step, consider the array between
lowandhighindices. - Calculate the
midindex. - If the element at the
midindex is equal to thetargetvalue, we returnmid. - If the element at
midis greater than thetarget:- Change the index
hightomid - 1. - The value of
lowremains the same.
- Change the index
- If the element at
midis less than thetarget:- Change
lowtomid + 1. - The value of
highremains the same.
- Change
- When the value of
lowis greater than the value ofhigh, this indicates that thetargetdoesn’t exist. Hence,-1is returned.
Time complexity
The time complexity of this solution is logarithmic, .
Space complexity
The space complexity of this solution is constant, .
Solution 2: Recursive
In this solution, we will implement the binary search algorithm recursively. At each step, the search function calls itself using either the right half or the left half of the sorted array.
Let’s look at another example below:
Time complexity
The time complexity of this solution is logarithmic, .
Space complexity
The space complexity of this solution is logarithmic, because the recursive approach consumes memory on the stack.
Binary search applications
- Search engines: It helps to efficiently search through large indexed databases.
- Libraries: Locating books in a catalog organized by some order.
- Databases: Quick retrieval of records from sorted data.
- Genome Analysis: Finding sequences within large genetic databases.
- E-commerce: Searching through sorted product listings.