๐ Binary Search in an Ordered Array
1๏ธโฃ Introduction
Binary Search is an efficient searching algorithm used to find an element in a sorted (ordered) array.
It works by repeatedly dividing the search space into two halves.
2๏ธโฃ Precondition
โ The array must be sorted (ascending or descending)
3๏ธโฃ Working Principle
- Find the middle element
- Compare it with the target (key)
- If equal โ element found
- If key < middle โ search in left half
- If key > middle โ search in right half
Repeat until:
- Element is found OR
- Search space becomes empty
4๏ธโฃ Algorithm (Iterative Binary Search)
๐น Pseudocode
BinarySearch(A, n, key):
low = 0
high = n - 1
while low <= high:
mid = (low + high) / 2
if A[mid] == key:
return mid
else if key < A[mid]:
high = mid - 1
else:
low = mid + 1
return -1 // element not found
5๏ธโฃ Example (Step-by-Step)
๐น Given Array (Sorted):
A = [2, 5, 8, 12, 16, 23, 38, 56]
๐น Search Key = 23
๐น Step 1
low = 0, high = 7
mid = 3 โ A[3] = 12
23 > 12 โ Search right half
๐น Step 2
low = 4, high = 7
mid = 5 โ A[5] = 23
โ Element found at index 5
6๏ธโฃ Time Complexity
| Case | Complexity |
|---|---|
| Best Case | O(1) |
| Average Case | O(log n) |
| Worst Case | O(log n) |
๐ Each step reduces problem size by half.
7๏ธโฃ Space Complexity
- Iterative version โ O(1)
- Recursive version โ O(log n) (stack space)
8๏ธโฃ Characteristics of Binary Search
โ Very efficient for large datasets
โ Requires sorted data
โ Reduces search space by half each step
9๏ธโฃ Advantages
- Fast searching (logarithmic time)
- Suitable for large data
- Fewer comparisons
๐ Disadvantages
- Works only on sorted arrays
- Not suitable for dynamic data (frequent insert/delete)
- Requires random access (not suitable for linked lists)
1๏ธโฃ1๏ธโฃ Comparison: Linear Search vs Binary Search
| Feature | Linear Search | Binary Search |
|---|---|---|
| Requirement | Unsorted OK | Must be sorted |
| Time Complexity | O(n) | O(log n) |
| Efficiency | Low | High |
๐ Conclusion
Binary Search is one of the most efficient searching algorithms for sorted data.
It works by dividing the search space into halves, leading to logarithmic time complexity.
๐ Exam Tip
๐ Always mention:
- Sorted array condition
- Algorithm steps
- Example
- Complexity
