Binary search
Halve the search interval of a sorted array at each step.
Syllabus says: “Binary Search”
On this page · 14 sections
SORTED only! mid = (low + high)/2. Key smaller → high = mid − 1; bigger → low = mid + 1. Halves every time → O(log n).
Opening a dictionary: you jump to the middle, decide which half the word is in, and never look at the other half again.
Binary search on a sorted array compares the key with the middle element and continues in the left or right half accordingly, taking O(log n) time.
Learning objectives
- Write iterative binary search.
- Trace low, high and mid.
- Explain the O(log n) bound and the sorted-input precondition.
Definition
Binary search finds a key in an array sorted in ascending order by comparing it with the middle element a[mid], mid = ⌊(low + high)/2⌋, and discarding the half that cannot contain the key.
How it works
- low = 0, high = n − 1.
- While low ≤ high: compute mid. If a[mid] = key, return mid.
- If a[mid] < key the key can only be to the right: low = mid + 1. Otherwise high = mid − 1.
- If the loop ends, the key is absent.
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm
- 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.
Pseudocode used by the animated lab · the lines highlighted in the visualizer
- 1BinarySearch(a, n, x) low ← 0; high ← n − 1
- 2while low ≤ high: mid ← ⌊(low + high)/2⌋
- 3if a[mid] = x
- 4return mid
- 5else if a[mid] < x: low ← mid + 1
- 6else: high ← mid − 1
- 7return −1
C implementation
binary_search.ctested ✓ 213/213 cases/* Binary Search — KTU PCCST303, Module 4 (lab-record style)
* The elements must be entered in ascending order. */
#include <stdio.h>
int main()
{
int a[100], n, i, key, low, high, mid, found = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements in ascending order:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter element to search: ");
scanf("%d", &key);
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
printf("Element found at position %d\n", mid + 1);
found = 1;
break;
}
else if (a[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
if (found == 0)
printf("Element not found\n");
return 0;
}
Sample input / output · search for 44 · real run, compiled with gcc
Enter number of elements: 8 Enter array elements in ascending order: 4 11 17 24 33 44 54 65 Enter element to search: 44 Element found at position 6
Bold = what you type. Everything else is printed by the program.
Complexity
Each comparison halves the interval, so at most ⌊log₂ n⌋ + 1 comparisons: O(log n) worst and average, O(1) best. Space O(1) iterative, O(log n) recursive.
Edge cases
- Unsorted input gives wrong answers — the simulator refuses it.
- In C, low + (high − low)/2 avoids integer overflow for very large arrays.
- With duplicates, the index returned is some occurrence, not necessarily the first.
Common mistakes
- Using low < high and missing a one-element interval.
- Setting low = mid (not mid + 1) — can loop forever.
Asked in KTU exams (1)
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
Sorted array required; O(log n); at most ⌊log₂ n⌋ + 1 comparisons.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing) §1.2 (Program 1.6), §7.2
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)