Binary Search in Data Structure: Algorithm and Time Complexity
Stop checking every value. Learn how the middle element can eliminate half the data at every step. Complete working diagrams, iterative and recursive C programs, duplicates and logarithmic complexity explained.
One comparison → keep just the half that can contain the target.
Binary Search is a divide-and-conquer searching algorithm that locates a target in sorted data by checking the middle element and repeatedly reducing the possible search interval by about half. On a sorted random-access array, binary search takes O(log n) worst-case time. Its iterative implementation needs O(1) auxiliary space; the recursive version normally needs O(log n) stack space.
Imagine opening a dictionary. You do not usually scan from page one. You open near the middle, decide whether the word comes before or after that page, and continue in only the relevant half. Binary search follows the same idea on an ascending or descending sorted array .
This chapter focuses on binary search algorithm in C, low-mid-high calculation, iterative and recursive binary search, first and last occurrence, lower and upper bounds, sorted-array conditions, dry runs, correctness, best/average/worst-case complexity and common programming mistakes. If the logic of writing step-by-step instructions is new, revise Algorithm in Data Structure: Characteristics, Steps and Examples .
Open the chapter roadmap
- Definition and prerequisites
- Low, mid and high working
- Algorithm and pseudocode
- Flowchart
- Found/not-found dry runs
- First/last occurrence and bounds
- Interactive search simulator
- Time complexity derivation
- Space and correctness
- Iterative C program
- Recursive C program
- C program for duplicates/bounds
- Descending-order C program
- Comparison and applications
- Mistakes and interview tips
- Solved exam questions
- MCQs, FAQs and revision
What Is Binary Search in Data Structure?

Binary Search is a searching technique for an ordered collection. In an ascending sorted array, compare the target with the middle element. If it is smaller, discard the middle and the right side. If it is larger, discard the middle and the left side. Repeat until the value is found or the interval becomes empty.
Sorted data is essential
An array such as [3, 7, 12, 18, 23, 29, 34] is valid for ascending binary search. The unsorted order [18, 3, 34, 7, 12] is not.
Why array access matters
Each comparison uses
a[mid].
A normal array accesses this element
in O(1) time. A linked list generally
needs traversal to reach its
middle node.
Successful and failed search
When a match is found, return the
zero-based index.
If low > high,
no valid candidate remains,
so return -1.
Divide-and-conquer strategy
Divide the search range using its middle; choose only one side; repeat. Unlike merge sort, binary search does not need to process both halves.
Binary search is a searching algorithm, not a separate data structure. It also helps find insertion positions, first/last duplicates and transition points in monotonic conditions.
How Binary Search Works: Low, Mid and High
For an ascending array with n elements,
start with low = 0
and high = n - 1.
While low <= high,
calculate the middle:
The division uses integer arithmetic
in C. This formula is preferred over
(low + high)/2
because adding two very large positive
indices could overflow a signed integer.
- If a[mid] == key, the standard algorithm returns mid. With duplicates, this may be any matching index.
-
If a[mid] < key,
search right by setting
low = mid + 1. -
If a[mid] > key,
search left by setting
high = mid - 1. -
Continue while
low <= high. Otherwise return -1.
a[mid].
Binary Search Algorithm and Pseudocode
The following is a standard iterative binary search algorithm for ascending sorted arrays . It returns a match if one exists, and -1 otherwise.
- Read the sorted array, number of elements n and target key.
-
Initialize
low = 0,high = n - 1. -
While
low <= high, setmid = low + (high - low)/2. -
If
a[mid] == key, return mid. -
If
a[mid] < key, setlow = mid + 1; otherwise sethigh = mid - 1. - If the loop ends, return -1 because the value is absent.
The recursive binary search
algorithm does the same
comparison, but instead of updating
the indices in a loop, it calls itself
on the chosen half.
Its base case is
low > high.
Binary Search Flowchart Explained
In an exam flowchart, use oval for start/end, rectangle for assignments, diamond for conditions and parallelogram for result output. The following compact text flow shows the decisions:
When choosing either side, exclude the middle because it has already been compared. That exclusion helps guarantee the interval shrinks and the algorithm terminates.
Binary Search Dry Run: Found and Not Found Examples
Use [3, 7, 7, 7, 12, 18, 23, 29, 34] . All positions are zero-based, n = 9. First find 23.
| Step | low | high | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 12 | 23 > 12 → low = 5 |
| 2 | 5 | 8 | 6 | 23 | Found at index 6 |
Unsuccessful Search: Find 25
| Step | low | high | mid | Value | Next range |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 12 | 5 to 8 |
| 2 | 5 | 8 | 6 | 23 | 7 to 8 |
| 3 | 7 | 8 | 7 | 29 | 7 to 6 (empty) |
Now low = 7
and high = 6,
so the while condition fails.
Return -1.
The target 25 does not exist
in the array.
Binary Search for First and Last Occurrence of an Element
In a sorted array containing duplicate values, ordinary binary search returns one matching index, not necessarily the first or last . To find boundaries, remember a match and keep searching toward the relevant side.
First occurrence
When a[mid] == key,
save answer = mid
and continue left with
high = mid - 1.
Stop with the earliest
matching index.
Last occurrence
When a[mid] == key,
save answer = mid
and continue right with
low = mid + 1.
Stop with the latest
matching index.
For
[3, 7, 7, 7, 12, 18, 23, 29, 34]
,
key 7 has first index 1
and last index 3.
Therefore its occurrence count is
3 - 1 + 1 = 3.
Lower Bound and Upper Bound
lower_bound(key)
is the first index where
a[i] >= key.
upper_bound(key)
is the first index where
a[i] > key.
If none exists, the returned
insertion-position index is n.
For a sorted ascending array,
upper_bound - lower_bound
gives the number of occurrences.
These versions use the half-open interval
[low, high)
with initial high = n,
as shown in the C program below.
Both bounds take O(log n) time on an ascending sorted array. They also work for a target that is missing: then lower and upper bounds may be equal, so count is zero.
Interactive Binary Search Simulator: Any, First and Last Match
The interactive lab uses the sorted array [3, 7, 7, 7, 12, 18, 23, 29, 34] . Choose Any match, First occurrence or Last occurrence and try targets 7, 23, 25 or 34. Use Next Step to see each middle comparison, or Run All to finish the trace.
The Halving Console
0 comparisonsBlue = current midpoint; faded = removed from consideration; amber dashed = saved match; green = final returned index. This is a learning simulator and does not send or store your inputs.
Binary Search Time Complexity: Best, Average and Worst Case
Binary search does not check every array element. It reduces the active interval from n items to roughly n/2, then n/4, n/8 and so on. Let k be the number of halving steps until only about one candidate remains:
For an already sorted array, standard binary search therefore needs O(log n) worst-case time. Under the usual successful-search distribution, average-case time is also Θ(log n). A lucky first midpoint match takes one comparison, which gives best-case O(1).
| Situation | Key comparisons | Time complexity | Reason |
|---|---|---|---|
| Best case | 1 | Θ(1) | Middle element matches immediately |
| Average case (usual model) | Proportional to log n | Θ(log n) | Halving continues over several levels |
| Worst case | At most floor(log₂ n) + 1 for n ≥ 1 in standard inclusive search | Θ(log n) | Target is absent or found near deepest level |
| Empty array | 0 | Θ(1) control work | Loop does not execute |
Number of Comparisons for Different Input Sizes
| Array size n | Illustrative upper bound on key checks | Linear search worst-case checks |
|---|---|---|
| 8 | 4 | 8 |
| 16 | 5 | 16 |
| 1,024 | 11 | 1,024 |
| 1,000,000 | 20 | 1,000,000 |
The logarithmic bound is a count of midpoint checks, not a real-world timing benchmark . Actual runtime also depends on memory access, data layout, branch behaviour and the time needed to sort or maintain the array. If the data is unsorted and sorted only for one search, add the sorting cost to the overall task.
Recurrence Relation
Each step performs constant comparison
work and retains at most half
the candidates.
A standard worst-case recurrence is
T(n) = T(n/2) + O(1)
for n > 1,
yielding T(n) = O(log n).
Binary Search Space Complexity and Why It Is Correct
Iterative binary search
Uses only low, high, mid and target variables. Auxiliary space = O(1), independent of input size. The input array's memory is not extra working space.
Recursive binary search
Each recursive call retains its own local state. Maximum call depth is O(log n), so auxiliary stack space = O(log n) .
Correctness: The Search Interval Invariant
For an ascending sorted array, an essential invariant is: if the target exists among the remaining candidates, it lies within indices low through high . At each midpoint comparison, the sorted property proves one excluded portion cannot contain the target. When a match is found, its index is correct. When low becomes greater than high, no candidates remain, proving the not-found result.
Termination: For every unsuccessful step, either low increases beyond mid or high decreases below mid. The interval becomes strictly smaller and cannot shrink forever. When duplicates exist, boundary algorithms maintain a saved answer and keep the invariant appropriate to finding the leftmost or rightmost match.
Iterative Binary Search in C Using Array and User Input
This full binary search program in C takes sorted array elements and a target from the user. It checks whether the input is non-decreasing before searching, so an accidental unsorted input does not silently produce a misleading result. It returns a matching zero-based index or -1.
#include <stdio.h>
#define CAPACITY 100
int binarySearch(const int a[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == key) return mid;
if (a[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
int main(void) {
int a[CAPACITY], n, key;
printf("Enter array size (0 to 100): ");
if (scanf("%d", &n) != 1 || n < 0 || n > CAPACITY) {
puts("Invalid array size.");
return 1;
}
printf("Enter %d ascending sorted integers:\n", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) {
puts("Invalid element.");
return 1;
}
if (i > 0 && a[i] < a[i - 1]) {
puts("Error: array is not sorted ascending.");
return 1;
}
}
printf("Enter target: ");
if (scanf("%d", &key) != 1) {
puts("Invalid target.");
return 1;
}
int index = binarySearch(a, n, key);
if (index == -1)
printf("%d not found.\n", key);
else
printf("%d found at index %d (position %d).\n",
key, index, index + 1);
return 0;
}
Explanation: For this 7-element array the first mid is index 3 (value 18); since 23 is greater, low becomes 4. The next mid is index 5 (29), so high becomes 4. Then mid 4 equals 23. The function returns 4. It is valid for duplicate values, but does not guarantee which duplicate it will return.
Compile in VS Code:
Save as binary_search_iterative.c
and run
gcc -std=c11 -Wall -Wextra binary_search_iterative.c -o binary_search_iterative.
Then launch
./binary_search_iterative
on Linux/macOS or
binary_search_iterative.exe
on Windows.
Recursive Binary Search in C with Base Case
Recursive binary search
uses the same midpoint logic,
but calls itself on the left
or right half.
The stopping condition is
low > high.
Every call receives a smaller range,
so the stack depth grows O(log n).
#include <stdio.h>
int binaryRecursive(const int a[], int low,
int high, int key) {
if (low > high) return -1;
int mid = low + (high - low) / 2;
if (a[mid] == key) return mid;
if (key < a[mid]) {
return binaryRecursive(a, low, mid - 1, key);
}
return binaryRecursive(a, mid + 1, high, key);
}
int main(void) {
int a[] = {3, 7, 12, 18, 23, 29, 34};
int n = (int)(sizeof a / sizeof a[0]);
printf("Index of 23: %d\n",
binaryRecursive(a, 0, n - 1, 23));
printf("Index of 25: %d\n",
binaryRecursive(a, 0, n - 1, 25));
return 0;
}
The recursion changes
low or high
on every unsuccessful call.
It returns -1 if the range
becomes empty.
If recursion is still new,
the site's
Tower of Hanoi Using Recursion
chapter offers another complete example
of recursive base cases and
shrinking subproblems.
Binary Search in C for First, Last, Lower Bound and Upper Bound
Many interview and semester questions ask: Find the first position of a repeated element , find the last occurrence or count duplicates in a sorted array. The following program handles all these cases using two binary searches. It uses a half-open search interval [low, high) , where high starts at n.
#include <stdio.h>
/* First index with a[i] >= key; n if none. */
int lowerBound(const int a[], int n, int key) {
int low = 0, high = n;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] < key) low = mid + 1;
else high = mid;
}
return low;
}
/* First index with a[i] > key; n if none. */
int upperBound(const int a[], int n, int key) {
int low = 0, high = n;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid] <= key) low = mid + 1;
else high = mid;
}
return low;
}
int main(void) {
int a[] = {3, 7, 7, 7, 12, 18, 23, 29, 34};
int n = (int)(sizeof a / sizeof a[0]);
int key = 7;
int lb = lowerBound(a, n, key);
int ub = upperBound(a, n, key);
int count = ub - lb;
int first = count ? lb : -1;
int last = count ? ub - 1 : -1;
printf("Lower bound index: %d\n", lb);
printf("Upper bound index: %d\n", ub);
printf("First occurrence: %d\n", first);
printf("Last occurrence: %d\n", last);
printf("Number of occurrences: %d\n", count);
return 0;
}
Important distinction:
Unlike standard binary search returning
-1 for a missing key,
lowerBound and
upperBound always return
a valid insertion-position index
between 0 and n.
Compare the two returned positions
to calculate the count.
If count == 0,
both first and last are -1.
These operations remain O(log n)
time and O(1) auxiliary space.
Binary Search on a Descending Sorted Array in C
Binary search also works on an array sorted in descending order. What changes? If the middle value is smaller than the target, the target must be further left; if it is larger, search right. Reversing comparisons correctly is the key.
#include <stdio.h>
int binaryDescending(const int a[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == key) return mid;
if (a[mid] < key) high = mid - 1;
else low = mid + 1;
}
return -1;
}
int main(void) {
int a[] = {90, 75, 62, 48, 30, 15, 4};
int n = (int)(sizeof a / sizeof a[0]);
printf("Index of 62: %d\n",
binaryDescending(a, n, 62));
printf("Index of 50: %d\n",
binaryDescending(a, n, 50));
return 0;
}
Both ascending and descending implementations have O(log n) worst-case time. The comparison rule must be consistent with the input order. In real applications, searching an ordered list of strings also needs a consistent string comparator, rather than integer comparison.
Binary Search vs Linear Search: Comparison and Applications
| Feature | Linear Search | Binary Search |
|---|---|---|
| Requires sorted array? | No | Yes, according to comparison order |
| Approach | Check sequentially | Check midpoint and halve candidates |
| Best-case time | O(1) | O(1) |
| Average/worst time | O(n) | O(log n) on indexed sorted array |
| Iterative auxiliary space | O(1) | O(1) |
| Good fit | Small or unsorted collections | Repeated searches on large sorted arrays |
Where Is Binary Search Used?
- Dictionary-style lookup: Locate an ordered word or numeric key among sorted entries.
- Database indexes: Ordered index pages often use searching principles, although real B-tree/B+tree structures have distinct algorithms and costs.
- First/last occurrence: Find the start and end of a repeated value in a sorted array.
- Insertion position: Calculate where a new key belongs with a lower-bound or upper-bound operation.
- Searching a monotonic answer: When feasibility changes from false to true at a boundary, binary search can locate that boundary if the monotonicity condition holds.
- Threshold finding: Determine the minimum acceptable capacity, time or resource level for a monotonic condition.
Trade-off: If a large array is already sorted and many lookups are planned, binary search is attractive. If the data changes frequently, keeping it sorted may require expensive insertions or reorganisations. A hash table or balanced tree may suit some workloads better. Linear scanning is still reasonable for small inputs.
Common Binary Search Mistakes and Memory Tricks
- Searching unsorted data: The left/right decision is invalid unless ordering is consistent.
-
Wrong loop condition:
Standard inclusive search uses
low <= high; half-open bound search useslow < high. Do not mix templates without changing the interval rules. -
Forgetting +1 or −1:
With an inclusive interval,
after rejecting mid, update
low = mid + 1orhigh = mid - 1. -
Overflow-prone midpoint:
Prefer
low + (high - low) / 2for non-negative valid indices. - Returning first duplicate incorrectly: Ordinary binary search returns a matching index, not necessarily the first. Use boundary search.
-
Confusing index and value:
midis an index;a[mid]is the element. - Ignoring array access cost: Array indexing is O(1), but reaching a linked list's middle node usually is not.
-
Forgetting n = 0:
A correct implementation returns
-1 for an empty array without reading
a[0]. - Wrong descending comparison: Descending arrays require reversed left/right decisions.
- Ignoring sorting cost: O(log n) is the search operation's cost when the input is already sorted.
Binary Search Important Questions with Answers (2, 5 and 10 Marks)
These are original university-exam-style and PYQ-style practice questions. They are not claimed as verified questions from a particular university paper.
Q1. Define binary search.
Binary search is a divide-and-conquer searching algorithm that finds an element in sorted data by comparing it with the middle item and repeatedly halving the possible interval.
Q2. What is the main condition for binary search?
The collection must be ordered using the same comparison rule as the search. Standard efficient array binary search assumes random access by index.
Q3. Write the safe mid formula.
mid = low + (high - low) / 2
.
Q4. State worst-case time and iterative space.
Worst-case time Θ(log n); auxiliary space O(1) for iterative binary search.
Q5. Explain binary search with an example.
Take sorted [3, 7, 12, 18, 23, 29, 34] and target 23. First mid is index 3 (18); because 23 is larger, search indices 4–6. Next mid is index 5 (29); because 23 is smaller, search index 4. It contains 23, so output index 4. The interval halves at each step.
Q6. Explain iterative vs recursive binary search.
Iterative binary search changes low/high inside a loop, so extra space is O(1). Recursive search calls itself with a smaller range and uses O(log n) stack space. Both have O(log n) worst-case time on sorted indexed arrays.
Q7. How do you find the first and last occurrence using binary search?
When the midpoint equals the key, save the index. For first occurrence, continue left; for last occurrence, continue right. Another method uses lower and upper bounds. Both need O(log n) time.
Q8. Explain binary search algorithm, flowchart, C program and complexities.
Begin with its definition, requirement of sorting and a labelled low/mid/high array diagram. Write the six pseudocode steps in Section 3 and flowchart decisions from Section 4. Include the full iterative C program from Section 10. Then derive n/2k ≈ 1, giving k = log₂n, so worst-case time is Θ(log n), best is Θ(1), and average under the usual model is Θ(log n). Iterative auxiliary space is O(1); recursive stack is O(log n). End with suitable applications and common mistakes.
Q9. Trace unsuccessful binary search for 25.
For [3, 7, 7, 7, 12, 18, 23, 29, 34], low = 0, high = 8 gives mid 4 (12), so low = 5. Mid 6 (23) makes low = 7. Mid 7 (29) makes high = 6. Now low > high, so return -1 after three comparisons.
Binary Search MCQs, FAQs and Quick Revision
Practice MCQs with Answers
- Binary search requires? A. Unsorted array B. Sorted data C. Only a queue D. Random values. Answer: B.
- Worst-case time? A. O(n) B. O(log n) C. O(n²) D. O(1). Answer: B.
- When a[mid] < key in ascending array, next low is? A. mid B. mid − 1 C. mid + 1 D. high. Answer: C.
- What does standard binary search return on a failed lookup? A. 0 B. n C. -1 D. mid. Answer: C in our C programs.
- Iterative auxiliary space? A. O(n) B. O(1) C. O(log n) D. O(n²). Answer: B.
- Recursive auxiliary space? A. O(log n) B. O(n) C. O(n²) D. O(1). Answer: A.
- Does standard binary search always return first duplicate? A. Yes B. No. Answer: B; a bound variation is needed.
- For n = 9, low = 0, high = 8, the initial mid index is? A. 3 B. 4 C. 8 D. 9. Answer: B.
- Binary search uses which strategy? A. Brute-force only B. Divide and conquer C. Hash chaining D. BFS. Answer: B.
- lower_bound in ascending order finds? A. Last smaller B. First ≥ target C. Last equal always D. First greater always. Answer: B.
Frequently Asked Questions
What is binary search in simple words?
It finds an item in sorted data by checking the middle, then discarding the half that cannot contain the target. It repeats until found or no candidates remain.
Can binary search work on an unsorted array?
Not using the normal midpoint-and-discard rule. The data must be ordered consistently, or you should choose a different method. Sorting has its own processing cost.
Can binary search find duplicates?
Yes. Standard search returns some matching index. First and last occurrences can be found by continuing left/right after equality or using lower and upper bound searches.
What is the time complexity of binary search?
Best O(1); average and worst Θ(log n) under the usual model for a sorted indexed array. Its logarithmic complexity comes from halving the remaining interval at each step.
What is the space complexity of recursive binary search?
O(log n) auxiliary stack space in the worst case because each nested function call stores its current boundaries until the recursion returns.
What is the difference between lower bound and upper bound?
For an ascending sorted array, lower bound is the first position with value ≥ key. Upper bound is the first position with value > key. Their difference counts duplicates of the key.
Is binary search better than linear search?
For repeated lookups in a large already sorted array, binary search requires asymptotically fewer comparisons. For small or unsorted collections, linear search may be simpler and avoid the cost of sorting.
Can binary search be written for descending arrays?
Yes. Reverse the side-selection comparisons. A complete descending-order C program appears above.
One-minute revision
Sorted array required. Initial low = 0, high = n − 1. Safe middle formula. On comparison discard one side. Return index or -1.
Remember the complexities
Best Θ(1). Average Θ(log n). Worst Θ(log n). Iterative space O(1). Recursive stack O(log n). First/last bounds O(log n).
Conclusion: Search Smarter by Halving
Binary search becomes easy when you understand what sorting lets you prove. One middle comparison shows which half cannot contain the target. Correctly updating low and high repeats this idea until a match appears or the interval is empty.
For university exams and interviews, practise low–mid–high dry runs, write both iterative and recursive C code, explain O(log n) using repeated halving, and learn the boundary methods for duplicates. Knowing the reasoning is more useful than memorising only the formula.
