-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search.c
57 lines (56 loc) · 992 Bytes
/
binary_search.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
50
51
52
53
54
55
56
57
#include<stdio.h>
int depth;
int bin_search(int *A,int left,int right,int item)
{
depth ++;
int mid=0,position=0;
if(left==right)
{
if(A[left]==item)
{
return left;
}
else
{
return -1;
}
}
else
{
mid=(left+right)/2;
if(A[mid]==item)
{
position=mid;
}
else if((item<A[mid])&&(left<mid))
{
position=bin_search(A,left,mid-1,item);
}
else if((item>A[mid])&&(mid<right))
{
position=bin_search(A,mid+1,right,item);
}
else
{
position =-1;
}
return position;
}
}
int main()
{
int n;
scanf("%d",&n);
int A[n];
for(int i=0;i<n;i++)
{
scanf("%d",&A[i]);
}
int location=0;
int x;
scanf("%d",&x);
depth=0;
location=bin_search(A,0,n,x);
printf("%d\n%d",depth,location);
return 0;
}