Introduction
Binary Search Technique: Binary Search is an efficient algorithm
that finds the position of a target element in a sorted array by repeatedly dividing the search interval in half.
This method reduces the search space exponentially, making it much faster than linear search.
How can we search for an element?
- Start with a sorted array and two pointers (start and end) that define the search interval.
- Find the middle element of the interval and compare it with the target element.
- If the target matches the middle element, return its index.
- If the target is smaller than the middle element, narrow the search interval to the left half.
- If the target is larger than the middle element, narrow the search interval to the right half.
- Repeat the process until the target is found or the interval is empty.
Important Observations
- The input array must be sorted for the algorithm to work.
- The search space is halved with each iteration.
- The algorithm is efficient for large datasets.
Key Characteristics:
- Divide-and-conquer search technique.
- Efficient for large sorted datasets.
- In-place searching; no additional memory required.
Advantages:
- Fast and efficient for large datasets.
- Time complexity is logarithmic.
- Minimal memory usage.
Disadvantages:
- Requires the dataset to be sorted.
- Not suitable for small or unsorted datasets.
Time Complexity:
- Best Case: (O(1)) (target found at the middle).
- Average Case: (O(log n)).
- Worst Case: (O(log n)).