What Is Binary Search and Why Is It Useful?
Problem:
Given a sorted array. Find x in the array.
You can approach the problem similar to above with binary search. You could approach the problem using the linear search - interate every element and find x in the array. However, it isn’t very efficient and will take forever if you have a long array. Therefore in that case, binary search is the way to go.
Here’s the step in the binary search:
- Start with finding the midpoint of the array.
- Compare the midpoint with the targeted number (x).
- If midpoint is less than x, you know x is in the right side of the array after the midpoint.
- If midpoint is greater than x, you know x is in the left side of the array before the midpoint.
- Let’s say x is greater than the midpoint as appears in the example below. You know x is on the right side of the array, so you know to move the search to the right. You could do that by repeating the steps above, but this time narrow your search interval starting from the position next to mid (mid+1) to the end of the array.
- Repeat the same steps as above until you find x, or until the interval is empty.
Example:
Reference: