C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING

Search a Sorted Array Using Binary Search

Learn how to search a sorted array using binary search using a clear C program.

IntermediateBinary searchSorted arrayDivide and conquer

PROBLEM UNDERSTANDING

Input and expected output

Sample input
7
2 5 8 12 16 23 38
16
Sample output
Found at position 5

COMPLETE C PROGRAM

Complete C implementation

binary-search.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int size, values[100], target, left = 0, right, position = -1;

    scanf("%d", &size);
    if (size < 1 || size > 100) return 1;
    for (int index = 0; index < size; index++) scanf("%d", &values[index]);
    scanf("%d", &target);
    right = size - 1;
    while (left <= right) {
        int middle = left + (right - left) / 2;
        if (values[middle] == target) { position = middle; break; }
        if (values[middle] < target) left = middle + 1;
        else right = middle - 1;
    }
    if (position >= 0) printf("Found at position %d\n", position + 1);
    else printf("Not found\n");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Found at position 5
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Repeatedly discard the half that cannot contain the target; the input must already be sorted.
  3. Display the computed result.

Repeatedly discard the half that cannot contain the target; the input must already be sorted.

EFFICIENCY

Time and space complexity

Time complexity

O(log n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.