-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathBinarySearch
More file actions
45 lines (37 loc) · 977 Bytes
/
BinarySearch
File metadata and controls
45 lines (37 loc) · 977 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
//srishti1302
#include <stdio.h>
#define COMPARE(x,y) ( (x)<(y)?-1:(x)==(y)? 0 :1 )
int binsearch(int a[20],int k,int left,int right)
{
if(left<right)
{
int middle=(left+right)/2;
switch(COMPARE(a[middle],k))
{
case -1: return binsearch(a,k,middle+1,right);
break;
case 0: return middle;
break;
case 1: return binsearch(a,k,left,middle-1);
break;
}
}
return -1;
}
int main()
{
int n,a[20],k,res;
printf("Enter size of the array: ");
scanf("%d",&n);
printf("\nEnter the array elements:\n");
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the number to be searched:\n");
scanf("%d",&k);
res=binsearch(a,k,0,n-1);
if(res==-1)
printf("Element not found!!");
else
printf("\nThe number %d is found at positon %d in the given list",k,res+1);
return 0;
}