#include <stdio.h>
int binary_search(int arr[], int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2; // find middle index
if (arr[mid] == target) {
return mid; // target found
} else if (arr[mid] < target) {
low = mid + 1; // search right half
} else {
high = mid - 1; // search left half
}
}
return -1; // target not found
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13};
int target = 7;
int size = sizeof(arr) / sizeof(arr[0]);
int result = binary_search(arr, 0, size - 1, target);
if (result != -1) {
printf("Target %d found at index %d\n", target, result);
} else {
printf("Target %d not found in array\n", target);
}
return 0;
}int mid = low + (high - low) / 2; // find middle index
Calculate middle index to split the search range.
if (arr[mid] == target) { return mid; }
Check if middle element is the target; if yes, return index.
else if (arr[mid] < target) { low = mid + 1; }
If middle element is less than target, search right half.
If middle element is greater than target, search left half.
Target 7 found at index 3