Searching is a crucial part of many computer algorithms. Binary search is an efficient way to search for an element in a sorted array. In this post, we’ll implement binary search in C, explain its logic, and provide a fully working C program for beginners.
What is Binary Search?
Binary search is a divide-and-conquer algorithm. It repeatedly divides the search interval in half. If the value of the search key is less than the middle element, the algorithm continues in the left half. Otherwise, it continues in the right half.
Binary Search Algorithm Steps:
- Start with the left and right pointers.
- Find the middle index.
- If the middle element is the target, return its index.
- If the target is less than the middle, search in the left half.
- If the target is greater, search in the right half.
- Repeat until the element is found or the range is empty.
Binary Search in C – Full Program:
#include <stdio.h>
int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1; // Not found
}
int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 50;
int result = binarySearch(arr, size, target);
if (result != -1)
printf("Element found at index: %d\n", result);
else
printf("Element not found in the array.\n");
return 0;
}
Why Use Binary Search?
- Works on sorted arrays
- Faster than linear search
- Time complexity: O(log n)
Understanding binary search in C helps improve your algorithmic thinking and prepare you for interviews or competitive programming.