Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
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

AlgorithmBinary Search
  1. Step 1:
    Start.
  2. Step 2:
    Read the number of elements n.
  3. Step 3:
    Read the n elements into the array A in ascending order.
  4. Step 4:
    Read the element to be searched, key.
  5. Step 5:
    Set low = 0 and high = n-1.
  6. 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.
  7. Step 7:
    Display "Element not found".
  8. 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