binary search is also known as Binary retrieval; Split half search method; Binary search.
It is to search in sorted data.
#include <stdio.h>
// Find the position of x in the array arr[l..r]
// If not found, return -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// in the middle exactly
if (arr[mid] == x)
return mid;
// If the value is less than the middle value, then continue searching in the left half part
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// If the value is greater than the middle value, continue searching in the right half part
return binarySearch(arr, mid + 1, r, x);
}
// not found
return -1;
}
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);
(result == -1)
? printf("not found")
: printf("find x at : %d", result);
return 0;
}