2017-04-23 14:06:30 +03:00
|
|
|
#include <stdio.h>
|
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
// Recursive Function- It returns location of x assumiung array arr[l..r] is
|
|
|
|
// present, otherwise -1
|
2017-04-23 14:06:30 +03:00
|
|
|
|
|
|
|
int binarysearch(int arr[], int l, int r, int x)
|
|
|
|
{
|
2020-05-29 23:23:24 +03:00
|
|
|
if (r >= l)
|
|
|
|
{
|
|
|
|
int mid = l + (r - l) / 2;
|
2017-04-23 14:06:30 +03:00
|
|
|
|
|
|
|
// If element is present at middle
|
2020-05-29 23:23:24 +03:00
|
|
|
if (arr[mid] == x)
|
|
|
|
return mid;
|
2017-04-23 14:06:30 +03:00
|
|
|
|
|
|
|
// If element is smaller than middle
|
2020-05-29 23:23:24 +03:00
|
|
|
if (arr[mid] > x)
|
|
|
|
return binarysearch(arr, l, mid - 1, x);
|
2017-04-23 14:06:30 +03:00
|
|
|
|
|
|
|
// Else element is in right subarray
|
2020-05-29 23:23:24 +03:00
|
|
|
return binarysearch(arr, mid + 1, r, x);
|
|
|
|
}
|
2017-04-23 14:06:30 +03:00
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
// When element is not present in array
|
|
|
|
return -1;
|
2017-04-23 14:06:30 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(void)
|
|
|
|
{
|
2020-05-29 23:23:24 +03:00
|
|
|
// give function an array to work with
|
|
|
|
int arr[] = {2, 3, 4, 10, 40};
|
|
|
|
// get size of array
|
|
|
|
int n = sizeof(arr) / sizeof(arr[0]);
|
|
|
|
// set value to look for
|
|
|
|
int x = 10;
|
|
|
|
// set result to what is returned from binarysearch
|
|
|
|
int result = binarysearch(arr, 0, n - 1, x);
|
|
|
|
// print out result
|
|
|
|
(result == -1) ? printf("Element is not in the array\n")
|
|
|
|
: printf("Element is present at index %d\n", result);
|
|
|
|
return 0;
|
2017-04-23 14:06:30 +03:00
|
|
|
}
|