-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbinarySearch.c
49 lines (48 loc) · 958 Bytes
/
binarySearch.c
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
//binary search
int binarySearch(int arr[],int l,int r,int key)
{
if(l<=r)
{
int mid = (l+r)/2;
if(arr[mid]==key)
{
return mid;
}
if(arr[mid]<key)
{
int ans = binarySearch(arr,mid+1,r,key);
return ans;
}
else
{
int ans = binarySearch(arr,l,mid-1,key);
return ans;
}
}
return -1;
}
int main()
{
printf("Enter the size of the array\n");
int n;
scanf("%d",&n);
int arr[n];
printf("Enter the elements of the array in sorted order\n");
for(register int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the element to find\n");
int key;
scanf("%d",&key);
int index = binarySearch(arr,0,n,key);
if(index==-1)
{
printf("Not found!!!\n");
}
else
{
printf("Found at %d index\n",index);
}
}