B.Tech S3 (R) (FT/WP) Examination November 2025 (2024 Scheme)QP 06PCCST303112503Part B · Q16b3 marksCO4Module 4
Question 16b
Write algorithm to search an element in a sorted array using binary search.
Topics: Binary search
Watch this exact question run
Loading visualizer…
Solution
- Step 1:Start.
- Step 2:Read the number of elements n.
- Step 3:Read the n elements into the array A in ascending order.
- Step 4:Read the element to be searched, key.
- Step 5:Set low = 0 and high = n-1.
- Step 6:Repeat while low <= high:
- Set mid = (low + high) / 2.
- If A[mid] == key, display "Element found at position mid+1" and go to Step 8.
- Else if A[mid] < key, set low = mid + 1.
- Else set high = mid - 1.
- Step 7:Display "Element not found".
- Step 8:Stop.
The array must be sorted. The position shown is mid + 1 because C array indices start at 0.
Watch outPrecondition
The array must already be sorted in ascending order.
How to write it in the exam
Best O(1); average and worst O(log n) — at most ⌊log₂ n⌋ + 1 comparisons.
How this answer was verified
- Property test vs indexOf
- binary_search.c — exact output tested; found position = visualizer index + 1
- tests/step-algorithms.test.ts — same probes (low, high, mid) as the visualizer