-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbinarysearch.c
48 lines (47 loc) · 853 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
#include <stdio.h>
int binarysearch(int arr[],int l,int r,int key)
{
int index=-1;
while(l<=r)
{
int mid=(l+r)/2;
if(arr[mid]==key)
{
index=mid;
break;
}
if(key<arr[mid])
{
r=mid-1;
}
else
{
l=mid+1;
}
}
return index;
}
int main()
{
printf("Enter the size of the array\n");
int n;
scanf("%d",&n);
int arr[n];
printf("Enter the elements of array in sorted array\n");
for(register int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
int key;
printf("Enter the value to find\n");
scanf("%d",&key);
int ans = binarysearch(arr,0,n,key);
if(ans==-1)
{
printf("Not found\n");
}
else
{
printf("Element found at %d\n",ans);
}
}