Two centers in Dehradun — Kanwali Road & Premnagar

Binary Search in C – Practical Coding Questions with Step-by-Step Solutions

Pivot Edu Unit Practice & Tutorials

Introduction to Binary Search in C

Binary Search is an efficient searching algorithm used to find an element in a sorted array. Instead of checking every element one by one, it repeatedly divides the search range into two halves.

At each step, the algorithm compares the target value with the middle element. If the target is smaller, it searches the left half. If the target is larger, it searches the right half. If both values are equal, the search is successful.

How Binary Search Works

Consider the sorted array below and suppose we want to search for 40.

Array: 10 20 30 40 50 60 70 Index: 0 1 2 3 4 5 6 Step 1: low = 0, high = 6 mid = (0 + 6) / 2 = 3 arr[3] = 40 Target found at index 3!

Binary Search Formula

The middle index is calculated using:

mid = low + (high - low) / 2

This formula avoids potential integer overflow that can occur with (low + high) / 2 when working with very large indexes.

Important Conditions

  • The array must be sorted in ascending order for the programs below.
  • Use low, high and mid variables to control the search range.
  • If the target is smaller than the middle element, update high = mid - 1.
  • If the target is larger than the middle element, update low = mid + 1.
  • If low becomes greater than high, the target is not present.

Q1: Implement Iterative Binary Search in C

Problem: Write a C program to search for a given element in a sorted array using iterative Binary Search. Display the index if the element is found; otherwise, display an appropriate message.

Step-by-Step Solution

  1. Declare a sorted integer array and the target element.
  2. Initialize low to 0 and high to n - 1.
  3. Calculate the middle index using low + (high - low) / 2.
  4. Compare the middle element with the target.
  5. Update low or high depending on the comparison.
  6. Stop when the element is found or the search range becomes empty.
#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50, 60, 70};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 50;
    int low = 0, high = n - 1;
    int found = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == target) {
            found = mid;
            break;
        } else if (target < arr[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    if (found != -1) {
        printf("Element %d found at index %d\n", target, found);
    } else {
        printf("Element not found\n");
    }

    return 0;
}

Expected Output

Element 50 found at index 4

Q2: Implement Binary Search Using Recursion

Problem: Write a recursive C program to search for an element in a sorted array. The function should return the index of the element or -1 if it is not found.

Step-by-Step Solution

  1. Create a function named binarySearch() that accepts the array, low, high and target.
  2. Check the base condition: if low is greater than high, return -1.
  3. Calculate the middle index.
  4. If the middle element matches the target, return mid.
  5. If the target is smaller, recursively search the left half.
  6. Otherwise, recursively search the right half.
#include <stdio.h>

int binarySearch(int arr[], int low, int high, int target) {
    if (low > high) {
        return -1;
    }

    int mid = low + (high - low) / 2;

    if (arr[mid] == target) {
        return mid;
    }

    if (target < arr[mid]) {
        return binarySearch(arr, low, mid - 1, target);
    }

    return binarySearch(arr, mid + 1, high, target);
}

int main() {
    int arr[] = {5, 15, 25, 35, 45, 55, 65};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 35;

    int result = binarySearch(arr, 0, n - 1, target);

    if (result != -1) {
        printf("Element found at index %d\n", result);
    } else {
        printf("Element not found\n");
    }

    return 0;
}

Expected Output

Element found at index 3

Q3: Count the Number of Comparisons in Binary Search

Problem: Write a C program to search for an element and count how many times the target is compared with the middle element.

Step-by-Step Solution

  1. Initialize a comparison counter to zero.
  2. Run the normal iterative Binary Search algorithm.
  3. Increase the counter once whenever the middle element is checked against the target.
  4. Stop when the target is found or the search range becomes empty.
  5. Display the result and the total number of comparisons.
#include <stdio.h>

int main() {
    int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 14;
    int low = 0, high = n - 1;
    int comparisons = 0;
    int found = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;
        comparisons++;

        if (arr[mid] == target) {
            found = mid;
            break;
        } else if (target < arr[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    if (found != -1) {
        printf("Element found at index %d\n", found);
    } else {
        printf("Element not found\n");
    }

    printf("Total comparisons: %d\n", comparisons);
    return 0;
}

Expected Output

Element found at index 6 Total comparisons: 3

Q4: Find the First Occurrence of an Element in a Sorted Array

Problem: A sorted array may contain duplicate values. Write a C program using Binary Search to find the first occurrence of a given element.

Step-by-Step Solution

  1. Perform Binary Search as usual.
  2. When the target is found, store the current middle index as the answer.
  3. Continue searching in the left half because an earlier occurrence may exist.
  4. Update high to mid - 1 after finding a match.
  5. Return the stored index after the search finishes.
#include <stdio.h>

int firstOccurrence(int arr[], int n, int target) {
    int low = 0, high = n - 1;
    int answer = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == target) {
            answer = mid;
            high = mid - 1;
        } else if (target < arr[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return answer;
}

int main() {
    int arr[] = {10, 20, 20, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 20;

    int result = firstOccurrence(arr, n, target);

    if (result != -1) {
        printf("First occurrence of %d is at index %d\n", target, result);
    } else {
        printf("Element not found\n");
    }

    return 0;
}

Expected Output

First occurrence of 20 is at index 1

Q5: Find the Last Occurrence of an Element in a Sorted Array

Problem: Write a C program to find the last index of a target element in a sorted array containing duplicate values.

Step-by-Step Solution

  1. Initialize low, high and answer.
  2. Calculate the middle index in each iteration.
  3. If the middle element matches the target, store mid as the answer.
  4. Continue searching in the right half by updating low to mid + 1.
  5. Return the last stored matching index.
#include <stdio.h>

int lastOccurrence(int arr[], int n, int target) {
    int low = 0, high = n - 1;
    int answer = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == target) {
            answer = mid;
            low = mid + 1;
        } else if (target < arr[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return answer;
}

int main() {
    int arr[] = {5, 10, 10, 10, 15, 20, 25};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 10;

    int result = lastOccurrence(arr, n, target);

    if (result != -1) {
        printf("Last occurrence of %d is at index %d\n", target, result);
    } else {
        printf("Element not found\n");
    }

    return 0;
}

Expected Output

Last occurrence of 10 is at index 3

Q6: Count the Total Occurrences of an Element Using Binary Search

Problem: Write a C program to count how many times a target value appears in a sorted array. Use Binary Search to find its first and last occurrences.

Step-by-Step Solution

  1. Use a Binary Search function to find the first occurrence.
  2. Use another Binary Search function to find the last occurrence.
  3. If the first occurrence is -1, the element is not present.
  4. Otherwise, calculate the count using last - first + 1.
#include <stdio.h>

int firstOccurrence(int arr[], int n, int target) {
    int low = 0, high = n - 1, answer = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == target) {
            answer = mid;
            high = mid - 1;
        } else if (target < arr[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return answer;
}

int lastOccurrence(int arr[], int n, int target) {
    int low = 0, high = n - 1, answer = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == target) {
            answer = mid;
            low = mid + 1;
        } else if (target < arr[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return answer;
}

int main() {
    int arr[] = {2, 4, 4, 4, 4, 6, 8, 10};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 4;

    int first = firstOccurrence(arr, n, target);
    int last = lastOccurrence(arr, n, target);

    if (first == -1) {
        printf("Element not found\n");
    } else {
        printf("First occurrence: %d\n", first);
        printf("Last occurrence: %d\n", last);
        printf("Total occurrences: %d\n", last - first + 1);
    }

    return 0;
}

Expected Output

First occurrence: 1 Last occurrence: 4 Total occurrences: 4

Q7: Search an Element in an Empty or Single-Element Array

Problem: Write a C program that safely performs Binary Search when an array has only one element. Also handle the case where the array is empty.

Step-by-Step Solution

  1. Pass the array size to the search function.
  2. If n is zero, return -1 immediately.
  3. Otherwise, perform the normal Binary Search loop.
  4. Test the function with a one-element array and display the result.
#include <stdio.h>

int binarySearch(int arr[], int n, int target) {
    int low = 0;
    int high = n - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == target) {
            return mid;
        } else if (target < arr[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return -1;
}

int main() {
    int single[] = {75};
    int result = binarySearch(single, 1, 75);

    if (result != -1) {
        printf("Element found at index %d\n", result);
    } else {
        printf("Element not found\n");
    }

    printf("Empty array search result: %d\n", binarySearch(single, 0, 75));
    return 0;
}

Expected Output

Element found at index 0 Empty array search result: -1

Practice Challenges for Students

Try solving these additional problems independently. Use the examples above as a reference, but write your own complete C programs.

  1. Write a program to search for the smallest element in a sorted array using Binary Search.
  2. Write a program to find the insertion position of a target value in a sorted array.
  3. Write a program to find the first element greater than or equal to a given target.
  4. Write a program to find the last element smaller than or equal to a given target.
  5. Write a program to search for a value in a sorted array in descending order.

Binary Search vs Linear Search

FeatureLinear SearchBinary Search
Working methodChecks elements one by oneRepeatedly divides the search range in half
Sorted array requiredNoYes, for the implementation taught here
Best-case timeO(1)O(1)
Worst-case timeO(n)O(log n)
Iterative auxiliary spaceO(1)O(1)

Time and Space Complexity of Binary Search

  • Best Case – O(1): The target is found at the middle position in the first comparison.
  • Average Case – O(log n): The search range is repeatedly reduced by half.
  • Worst Case – O(log n): The algorithm continues dividing the range until the target is found or the range becomes empty.
  • Iterative Space Complexity – O(1): Only a fixed number of variables are used.
  • Recursive Space Complexity – O(log n): Recursive function calls use stack memory.

Key Takeaways

  • Binary Search works on sorted arrays.
  • The middle element determines which half should be searched next.
  • Iterative Binary Search uses a loop, while recursive Binary Search uses function calls.
  • First and last occurrence problems can be solved by continuing the search after finding a match.
  • Binary Search has logarithmic time complexity, making it efficient for large sorted arrays.

Learning at Pivot Edu Unit: Practise each program, change the sample array and target value, and observe how the search range changes. Understanding the logic is more important than memorising the code.

Frequently Asked Questions

⚡ Live Output