Pointer Assignment 10 — Binary Search in a Sorted Array Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Binary Search in a Sorted Array Using Pointers — Searching by Halving the Range

📑 On this page:
  • How Pointer-Based Binary Search Works
  • The Three Steps of Binary Search
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to implement binary search using low, high, and mid pointers
  • Why binary search works only when the array is sorted
  • How to calculate the middle pointer using low + (high - low) / 2
  • How to recover an array index from a pointer using pointer subtraction
  • Why binary search has O(log n) time complexity
  • How to avoid the common integer-overflow mistake while finding the middle position

How Pointer-Based Binary Search Works

Binary search is an efficient searching technique used only on a sorted array. Instead of checking every element one by one, it repeatedly compares the key with the middle element. If the key matches the middle element, the search ends. If the key is smaller, the search continues in the left half; if it is larger, the search continues in the right half.

In the pointer version, we use three pointers: low, high, and mid. The low pointer marks the beginning of the current search range, while high marks its end. The mid pointer points to the middle element of that range. After every comparison, one half of the range is discarded.

The middle pointer is calculated as mid = low + (high - low) / 2. This is safer than writing (low + high) / 2, because adding two large pointers or indexes directly can cause overflow. The expression high - low gives the number of elements between the two pointers, dividing it by 2 gives the offset, and adding that offset to low gives the middle position.

💡 In one line: Keep low and high pointers at the current search boundaries, compare the key with *mid, and repeatedly discard the half that cannot contain the key.

Diagram showing low, mid, and high pointers searching a sorted array using binary search

The Three Steps of Binary Search

Step Pointer operation Effect
1. Set the search boundarieslow = arr; and high = arr + n - 1;low points to the first element and high points to the last element
2. Find and compare the middle elementmid = low + (high - low) / 2;The key is compared with *mid to decide the next half
3. Reduce the search rangelow = mid + 1; or high = mid - 1;Half of the remaining elements are discarded in each step

Binary search depends completely on the sorted order of the array. If the array is sorted in ascending order, then every element to the left of mid is smaller than or equal to *mid, and every element to the right is greater than or equal to *mid. This ordering allows the algorithm to decide safely which half to keep and which half to discard.

If the array is not sorted, binary search may return the wrong result or fail to find an element that is actually present. Therefore, before applying binary search, the array must be arranged in ascending or descending order. In this program, we assume that the user enters the elements in ascending order.

Complete C Program

Program: binary search in a sorted array using pointers

#include <stdio.h>

#define MAX 100

/* Binary search using pointers.
   Returns the index of key, or -1 if not found. */
int binary_search(const int *arr, int n, int key) {
    const int *low = arr;             /* first element */
    const int *high = arr + n - 1;    /* last element */
    const int *mid;

    while (low <= high) {
        mid = low + (high - low) / 2; /* middle pointer */

        if (*mid == key) {
            return (int)(mid - arr);  /* pointer subtraction gives index */
        }
        else if (*mid < key) {
            low = mid + 1;            /* search right half */
        }
        else {
            high = mid - 1;           /* search left half */
        }
    }

    return -1;                        /* not found */
}

int main(void) {
    int arr[MAX];
    int n, key, i, result;

    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0 || n > MAX) {
        printf("Invalid size.\n");
        return 1;
    }

    printf("Enter %d integers in ascending order:\n", n);
    for (i = 0; i < n; i++) {
        if (scanf("%d", &arr[i]) != 1) {
            printf("Invalid input.\n");
            return 1;
        }
    }

    printf("Enter the key to search: ");
    if (scanf("%d", &key) != 1) {
        printf("Invalid key.\n");
        return 1;
    }

    result = binary_search(arr, n, key);

    if (result == -1) {
        printf("\n%d was not found in the array.\n", key);
    } else {
        printf("\n%d was found at index %d (position %d).\n",
               key, result, result + 1);
    }

    return 0;
}
                                    

Program Output

How many elements? 7
Enter 7 integers in ascending order:
10 20 30 40 50 60 70
Enter the key to search: 50

50 was found at index 4 (position 5).
                                

A second run, with a key that is not present:

How many elements? 7
Enter 7 integers in ascending order:
10 20 30 40 50 60 70
Enter the key to search: 55

55 was not found in the array.
                                

In the first run, the middle element is checked first. Since 50 is greater than the first middle value, the search moves to the right half. It then finds 50 at index 4. In the second run, the search range keeps shrinking until low becomes greater than high, so the function returns -1.

Step-by-Step Explanation

Let us understand how the pointers move during binary search.

1. The function signature

binary_search(const int *arr, int n, int key) receives a pointer to the first element, the number of elements, and the key to search. The const keyword tells the compiler that the function will only read the array and will not modify it.

2. Setting the low and high pointers

const int *low = arr; makes low point to the first element. const int *high = arr + n - 1; makes high point to the last element. Initially, the complete array is the search range.

3. Calculating the middle pointer

mid = low + (high - low) / 2; calculates the middle position safely. Here, high - low gives the number of elements between the two pointers. Dividing it by 2 gives the offset from low, and adding that offset to low gives the middle pointer.

4. Comparing the middle element

*mid gives the value stored at the middle position. If *mid == key, the element is found. The function returns (int)(mid - arr), which gives the index of the matching element.

5. Searching the right half

If *mid < key, the key must be on the right side of the middle element because the array is sorted in ascending order. Therefore, low is moved to mid + 1, and the left half is discarded.

6. Searching the left half

If *mid > key, the key must be on the left side of the middle element. Therefore, high is moved to mid - 1, and the right half is discarded.

7. Loop termination

The loop runs while low <= high. When low becomes greater than high, the search range is empty. This means the key is not present in the array, so the function returns -1.

8. Example trace

For the sorted array [10, 20, 30, 40, 50, 60, 70] and key = 50:

  • First iteration: low points to index 0, high points to index 6, and mid points to index 3. Since *mid = 40 and 40 < 50, move low to index 4.
  • Second iteration: low points to index 4 and high points to index 6. Now mid points to index 5. Since *mid = 60 and 60 > 50, move high to index 4.
  • Third iteration: low and high both point to index 4. Now mid also points to index 4. Since *mid = 50, the key is found and the function returns 4.

9. Why the array must be sorted

Binary search can discard half of the array only because the elements are arranged in order. If the array is unsorted, a value smaller than the middle element may still appear on the right side, so the algorithm cannot safely decide which half to discard.

10. Pointer version vs index version

The same algorithm can also be written using integer indexes:

int binary_search_index(const int arr[], int n, int key) {
    int low = 0, high = n - 1, mid;

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

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

    return -1;
}
                                

Both versions follow the same logic. The pointer version uses low, high, and mid as pointers, while the index version uses them as integer positions. The pointer version is useful for practicing pointer arithmetic, pointer subtraction, and pointer comparison.

11. Complexity summary

Time complexity is O(log n), because the search range is divided into half after every comparison. Best case is O(1), when the key is found at the middle position in the first comparison. Worst case is O(log n), when the key is found at the last possible step or is not present. Space complexity is O(1), because the iterative version uses only a few pointer variables.

🎯 Remember this: Binary search works only on a sorted array. Use low and high pointers for the search range, calculate mid = low + (high - low) / 2, and move low or high depending on whether the key is greater or smaller than *mid.

Frequently Asked Questions

1. Why does binary search require a sorted array?

Binary search decides whether to search the left or right half by comparing the key with the middle element. This decision is valid only when the array is sorted. In an unsorted array, the key may appear on either side of the middle element, so the algorithm cannot safely discard any half.

2. What does mid - arr return?

mid - arr returns the number of elements between the first element and the middle element. Since arr points to index 0, this difference is exactly the index of the middle element. For example, if mid points to the fifth element, mid - arr is 4.

3. Why is mid = low + (high - low) / 2 better than (low + high) / 2?

The expression low + (high - low) / 2 avoids overflow. If low and high are very large, adding them directly in (low + high) / 2 may exceed the maximum value that an integer can store. The safer form first calculates the difference, which is always smaller, and then adds half of it to low.

4. What happens if the array contains duplicate elements?

This program returns the index of one matching element, but not necessarily the first or last occurrence. If the array contains duplicates and you need the first occurrence, continue searching the left half even after finding a match. To find the last occurrence, continue searching the right half.

5. Can binary search be used on a descending array?

Yes, but the comparison logic must be reversed. In a descending array, if the key is greater than the middle element, search the left half; if the key is smaller, search the right half. The array must still be consistently sorted.

6. What is the time complexity of binary search?

The time complexity is O(log n), because each comparison removes half of the remaining elements. For an array of 1,000 elements, binary search needs at most about 10 comparisons. Its space complexity is O(1) for the iterative implementation because it uses only a fixed number of pointer variables.

💡 Tip: After implementing this program, try modifying it to find the first occurrence of a duplicate key, or write a recursive version using low and high pointers. Both variations strengthen your understanding of pointer-based searching.

📖 Related Tutorials

  • 9. Linear Search in an Array Using Pointers
  • 11. Reverse an Array Using Pointers
  • Reverse a String Using Pointers
  • Compare Two Strings Using Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 9. Linear Search in an Array Using Pointers   ||   Next Topic: -->> Swap Array Elements Using Pointers


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.