- Asked 4/14
- 2073 Magh · 8 marks
- 2070 Bhadra · 6 marks
- 2073 Bhadra · 3 marks
- 2072 Magh · 4 marks
Binary search with algorithm and example
Short answer
Binary search on a sorted array: compare key with middle element, discard half, repeat. Worst-case O(log n). Example: searching 41 in [5,12,18,23,30,41,56] finds it at index 5 after two comparisons.
Write down the algorithm for binary search with suitable example. Explain a binary search with example.
Binary search finds a key in a sorted array by repeatedly comparing it with the middle element and discarding the half that cannot contain it.
Algorithm
BINARYSEARCH(a, n, key)
1. low = 0, high = n - 1
2. while low <= high
3. mid = (low + high) / 2
4. if key == a[mid] return mid // found
5. else if key < a[mid] high = mid - 1 // search left half
6. else low = mid + 1 // search right half
7. return -1 // not found
int binarySearch(int a[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == key) return mid;
else if (key < a[mid]) high = mid - 1;
else low = mid + 1;
}
return -1;
}
Example: search 23 in 5, 12, 18, 23, 30, 41, 56 (index 0 to 6)
| Step | low | high | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 23 | equal, found |
Search 41 in the same list:
| Step | low | high | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 23 | 41 > 23, low = 4 |
| 2 | 4 | 6 | 5 | 41 | found at index 5 |
If the key is absent (say 20), low becomes greater than high and the search stops with "not found".
Complexity: each step halves the range, so the worst case is O(log₂ n) comparisons (best case O(1)). The list must already be sorted and stored in an array that allows direct access.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Binary search for 54 in sorted data · Data Structure and Algorithm, chapter 8
- Binary search for 89; hash functions · Data Structure and Algorithm, chapter 8
- Complexity of binary search · Data Structure and Algorithm, chapter 8
- Sequential vs binary search · Data Structure and Algorithm, chapter 8
- BST properties and recursive search · Data Structure and Algorithm, chapter 6
- Binary tree traversals; preorder of BST · Data Structure and Algorithm, chapter 6
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Binary file of 48 students; highest mark · Computer Programming, chapter 10
- Decoupled load flow assumptions and algorithm · Power System Analysis II, chapter 2 · asked 2×
- Bresenham's algorithm for all slopes · Computer Graphics, chapter 2