Binary search is a fundamental algorithm used in the world of programming to efficiently locate a target value within a sorted array. It operates by repeatedly dividing the search interval in half. In this tutorial, we’ll walk through the process of writing a program for binary search in the C programming language.
Binary Search Algorithm
The binary search algorithm follows these steps
- Take a sorted array as input.
- Define the search boundaries by setting
left
andright
indices. - Calculate the middle index
mid
of the array. - Compare the target value with the value at the
mid
index. - If the target matches the middle element, return the index.
- If the target is smaller, update the
right
index tomid - 1
. - If the target is larger, update the
left
index tomid + 1
. - Repeat until the element is found or the search interval becomes empty.
Binary Search Program in C
Let’s write a C program to perform a binary search on a sorted array of integers –
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1; // If the target element is not found
}
void main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 23;
int result = binarySearch(arr, 0, n - 1, target);
if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found in the array\n");
}
Output
Binary Search C Program Explanation
binarySearch
function: Performs the binary search by updating the search boundaries and returning the index of the target element.main
function: Initializes a sorted array and a target value, callsbinarySearch
, and displays the result.