EXPERIMENT – 9B
AIM To perform binary search
THEORY
Binary search is another algorithm for searching. Perhaps the most efficient algorithm. Binary search
is a searching algorithm used to find an element's position in a sorted array. It works by repeatedly
dividing in half the portion of the array that could contain the element, until you've narrowed down
the possible locations to just one. This algorithm works efficiently with sorted arrays and has a time
complexity of O(log n).
C CODE
#include <stdio.h>
// Function to perform binary search
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if target is present at mid
if (arr[mid] == target)
return mid;
// If target greater, ignore left half
if (arr[mid] < target)
left = mid + 1;
// If target is smaller, ignore right half
else
right = mid - 1;
// If target is not found in array
return -1;
}
int 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 is not present in array\n");
else
printf("Element is present at index %d\n", result);
return 0;
OUTPUT
RESULT
Binary search has been implemented in arrays.