Binary Search in Data Structure: Algorithm and Time Complexity

Data Structure / Chapter 38 / The Halving Lab

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.

Divide and Conquer Sorted Arrays 4 C Programs Interactive Binary Search
Quick Answer / Definition

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
  1. Definition and prerequisites
  2. Low, mid and high working
  3. Algorithm and pseudocode
  4. Flowchart
  5. Found/not-found dry runs
  6. First/last occurrence and bounds
  7. Interactive search simulator
  8. Time complexity derivation
  9. Space and correctness
  10. Iterative C program
  11. Recursive C program
  12. C program for duplicates/bounds
  13. Descending-order C program
  14. Comparison and applications
  15. Mistakes and interview tips
  16. Solved exam questions
  17. MCQs, FAQs and revision
01 / Know the precondition

What Is Binary Search in Data Structure?

Binary Search in Data Structure: Algorithm and Time Complexity

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.

02 / Three essential pointers

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:

mid = low + (high - low) / 2

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.

0 1 2 3 4 5 6 7 8
3 7 7 7 12 18 23 29 34
Sorted array: 9 elements, low = 0, high = 8, mid = 4, a[mid] = 12. Middle is highlighted blue.
  1. If a[mid] == key, the standard algorithm returns mid. With duplicates, this may be any matching index.
  2. If a[mid] < key, search right by setting low = mid + 1.
  3. If a[mid] > key, search left by setting high = mid - 1.
  4. Continue while low <= high. Otherwise return -1.
Beginner tip: low and high are array indices, not the smallest and largest values themselves. mid is also an index. To compare the target, read a[mid].
03 / Write the steps

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.

  1. Read the sorted array, number of elements n and target key.
  2. Initialize low = 0, high = n - 1.
  3. While low <= high, set mid = low + (high - low)/2.
  4. If a[mid] == key, return mid.
  5. If a[mid] < key, set low = mid + 1; otherwise set high = mid - 1.
  6. If the loop ends, return -1 because the value is absent.
BINARY_SEARCH(a, n, key): low = 0 high = n - 1 while low <= high: mid = low + (high - low) / 2 if a[mid] == key: return mid if a[mid] < key: low = mid + 1 else: high = mid - 1 return -1

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.

04 / Flowchart

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:

YES: calculate mid → a[mid] == key? → YES Return mid
NO: a[mid] < key? → YES low = mid + 1 → Repeat
NO: a[mid] > key → high = mid − 1 → Repeat
low ≤ high? NO → Return −1 → STOP

When choosing either side, exclude the middle because it has already been compared. That exclusion helps guarantee the interval shrinks and the algorithm terminates.

05 / Trace each decision

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
0 1 2 3 4 5 6 7 8
3 7 7 7 12 18 23 29 34
After checking 12 at mid 4, only indices 5–8 remain possible. The next mid is 6, where 23 is found.

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.

Edge cases: n = 0 means low = 0, high = -1, so no comparisons are made. A one-element array has low = high = 0 and performs one comparison. In both cases, the loop condition remains safe.
06 / Duplicate-aware search

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.

Array: [3, 7, 7, 7, 12, 18, 23, 29, 34] key = 7 lower_bound(7) = 1 upper_bound(7) = 4 count = 4 - 1 = 3 First = 1, Last = 3

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.

07 / Use the live visualizer

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 comparisons
03
17
27
37
412
518
623
729
834

Ready. Press Start Search, then Next Step.

Range: waiting Result: waiting

Blue = 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.

Practice: Search 7 in Any mode and note that the returned index depends on the midpoint path. Then choose First (index 1) and Last (index 3). For 25, every mode should finish with -1.
08 / Prove logarithmic speed

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:

n / 2^k ≈ 1 2^k ≈ n k ≈ log2(n) Worst-case time = Θ(log n) Best-case time = Θ(1)

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).

09 / Space and proof of correctness

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.

Practical nuance: Although binary search can conceptually be used on a sorted linked list, finding the middle by traversal costs additional time. For conventional singly linked lists, this is generally inferior to an array-based binary search. Use a representation that supports fast indexed access when appropriate.
10 / Complete C program 1

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.

binary_search_iterative.c Runnable C11 / input validation
#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;
}
Enter array size (0 to 100): 7 Enter 7 ascending sorted integers: 3 7 12 18 23 29 34 Enter target: 23 23 found at index 4 (position 5).

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.

11 / Complete C program 2

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).

binary_search_recursive.c Runnable C11 / recursive
#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;
}
Index of 23: 4 Index of 25: -1

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.

12 / Complete C program 3

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.

binary_search_bounds.c Runnable C11 / duplicates
#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;
}
Lower bound index: 1 Upper bound index: 4 First occurrence: 1 Last occurrence: 3 Number of occurrences: 3

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.

13 / Complete C program 4

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.

binary_search_descending.c Runnable C11 / reverse sorted
#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;
}
Index of 62: 2 Index of 50: -1

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.

14 / Choose the right technique

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.

15 / Debugging and interviews

Common Binary Search Mistakes and Memory Tricks

  1. Searching unsorted data: The left/right decision is invalid unless ordering is consistent.
  2. Wrong loop condition: Standard inclusive search uses low <= high; half-open bound search uses low < high. Do not mix templates without changing the interval rules.
  3. Forgetting +1 or −1: With an inclusive interval, after rejecting mid, update low = mid + 1 or high = mid - 1.
  4. Overflow-prone midpoint: Prefer low + (high - low) / 2 for non-negative valid indices.
  5. Returning first duplicate incorrectly: Ordinary binary search returns a matching index, not necessarily the first. Use boundary search.
  6. Confusing index and value: mid is an index; a[mid] is the element.
  7. Ignoring array access cost: Array indexing is O(1), but reaching a linked list's middle node usually is not.
  8. Forgetting n = 0: A correct implementation returns -1 for an empty array without reading a[0].
  9. Wrong descending comparison: Descending arrays require reversed left/right decisions.
  10. Ignoring sorting cost: O(log n) is the search operation's cost when the input is already sorted.
Memory trick: COMPARE → CHOOSE HALF → REPEAT . If target is smaller than middle, go LEFT (ascending order). If larger, go RIGHT. First = keep going LEFT after match; Last = keep going RIGHT.
16 / Exam notebook

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.

2 Marks

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.

5 Marks

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.

10 Marks

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.

17 / Test yourself

Binary Search MCQs, FAQs and Quick Revision

Practice MCQs with Answers

  1. Binary search requires? A. Unsorted array B. Sorted data C. Only a queue D. Random values. Answer: B.
  2. Worst-case time? A. O(n) B. O(log n) C. O(n²) D. O(1). Answer: B.
  3. When a[mid] < key in ascending array, next low is? A. mid B. mid − 1 C. mid + 1 D. high. Answer: C.
  4. What does standard binary search return on a failed lookup? A. 0 B. n C. -1 D. mid. Answer: C in our C programs.
  5. Iterative auxiliary space? A. O(n) B. O(1) C. O(log n) D. O(n²). Answer: B.
  6. Recursive auxiliary space? A. O(log n) B. O(n) C. O(n²) D. O(1). Answer: A.
  7. Does standard binary search always return first duplicate? A. Yes B. No. Answer: B; a bound variation is needed.
  8. For n = 9, low = 0, high = 8, the initial mid index is? A. 3 B. 4 C. 8 D. 9. Answer: B.
  9. Binary search uses which strategy? A. Brute-force only B. Divide and conquer C. Hash chaining D. BFS. Answer: B.
  10. 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).

Chapter 38 / Completed

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.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources