-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathd11_binary_search.c
More file actions
46 lines (43 loc) · 969 Bytes
/
d11_binary_search.c
File metadata and controls
46 lines (43 loc) · 969 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
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<stdio.h>
#include<stdlib.h>
int binsearch(int *arr,int l,int n,int key);
int main(void)
{
int n,key,loc;
scanf("%d",&n);
int *arr = (int *)malloc(n*sizeof(int));
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
scanf("%d",&key);
loc = binsearch(arr,0,n,key);
if(loc == -1)
printf("Element %d is not present in the array.",key);
else
printf("Element %d is present in %d location.",key,loc);
return 0;
}
int binsearch(int *arr,int l,int n,int key)
{
int low = l,high = n,mid;
if(high >= low)
{
mid = (low+high)/2;
if(arr[mid] == key)
return mid;
else if(key > arr[mid])
{
low = mid + 1;
high = n;
return binsearch(arr,low,high,key);
}
else
{
low = 0;
high = mid - 1;
return binsearch(arr,low,high,key);
}
}
return -1;
}