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.
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
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Found at position 5
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Repeatedly discard the half that cannot contain the target; the input must already be sorted.
- 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.
