- 2069 Poush · 4+4 marks
Binary search for 54 in sorted data
Short answer
Repeatedly compare the key with the middle element, discarding half. For 8,15,36,40,41,54,62: mid=3 (40) → low=4; mid=5 (54) → found at index 5 in 2 comparisons.
Write down the algorithm for binary search. Show steps to search 54 from the given data 8, 15, 36, 40, 41, 54, 62 using binary search.
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;
}
Search 54 in 8, 15, 36, 40, 41, 54, 62 (index 0 to 6)
| Step | low | high | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 40 | 54 > 40, so low = 4 |
| 2 | 4 | 6 | 5 | 54 | equal, found |
Answer: 54 is found at index 5 (position 6) in 2 comparison steps.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Binary search with algorithm and example · Data Structure and Algorithm, chapter 8 · asked 4×
- 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
- Rankine's data, 8° curve, 187.62 m long chord · Surveying II, chapter 6
- Muskingum routing, K=36 hr, x=0.15 · Engineering Hydrology, chapter 7
- IC manufacturing steps; top-down F = xz + y · Embedded System, chapter 8
- Display records sorted by name from file · Computer Programming, chapter 10