Binary Search Explained (1)
Binary Search Explained (1)
Binary search is an efficient algorithm for finding the position of a target element
within a sorted list. It works by repeatedly dividing the search interval in half until the
target value is found or the interval is empty.
Key Points:
1. Initialize:
Start with two pointers: one pointing to the beginning of the list (low) and the other to
the end (high).
2. Divide:
Conquer: If the middle element equals the target, the search is successful.
If the target is less than the middle element, adjust the high pointer to mid - 1
(narrowing the search to the left half).
If the target is greater than the middle element, adjust the low pointer to mid + 1
(narrowing the search to the right half).
1.
Repeat:
1.
Repeat the process on the narrowed interval until the target is found or low > high,
indicating the target is not in the list.
Example:
1. Initial pointers:
1.
First iteration:
Java Implementation:
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
1. Initial List: Say you have a sorted list of size . Binary search divides the list in half
at each step:
General Rule: In binary search, each iteration (repetition) reduces the problem size
by a factor of 2, so it completes in time.
Algorithms with complexity are very efficient for large inputs. Even for a dataset of a
billion elements (), , meaning only about 30 iterations are needed.
BinarySearch(array, target):
low ← 0
high ← length(array) - 1
Real-World Analogy
Keep splitting the remaining section of the dictionary in half until you find the word
or run out of pages.