forked from 2015jamrajput/programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Search
More file actions
33 lines (32 loc) · 810 Bytes
/
Binary Search
File metadata and controls
33 lines (32 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
else if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
else
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main(void)
{
int n,x;
printf("Enter the Array length:-\n");
scanf("%d",&n);
int arr[n];
printf("Enter the Array elements:-\n");
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the element to be searched:-\n");
scanf("%d",&x);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present in array"): printf("Element is present at index %d",result);
return 0;
}