Recusive binary search
#include <stdio.h>
int binarySearchRecursive(int arr[], int low, int high, int x) {
if (high >= low) {
int mid = low + (high - low) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearchRecursive(arr, low, mid - 1, x);
return binarySearchRecursive(arr, mid + 1, high, x);
return -1;
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int x = 23;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearchRecursive(arr, 0, n - 1, x);
if (result == -1)
printf("Element not found in the array");
else
printf("Element found at index %d", result);
return 0;
Non Recursive
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int x)
{
while (low <= high) {
int mid = low + (high - low) / 2;
// Check if x is present at mid
if (arr[mid] == x)
return mid;
// If x greater, ignore left half
if (arr[mid] < x)
low = mid + 1;
// If x is smaller, ignore right half
else
high = mid - 1;
return -1;
// Driver code
int main(void)
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
if(result == -1) printf("Element is not present in array");
else printf("Element is present at index %d",result);