Skip to content

Commit c1c27ae

Browse files
authored
Merge pull request #972 from aamrin786/add-BinarySearch
Add Binary Search Program In C
2 parents 02f39b1 + bcb0147 commit c1c27ae

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

BinarySearch.c

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
int bs(int *,int ,int ,int );
4+
int main()
5+
{
6+
int *p,i,f,n,c,s=0,e;
7+
printf("ENTER THE NUMBER OF ELEMENTS WANT TO INPUT : ");
8+
scanf("%d",&n);
9+
p=(int *)malloc(n*sizeof(int));
10+
printf("\n\nENTER THE ELEMENTS IN ASCENDING ORDER \n\n");
11+
for(i=0;i<n;i++)
12+
{
13+
scanf("%d",(p+i));
14+
}
15+
e=n-1;
16+
printf("ENTER THE ELEMENT WANT TO SEARCH : ");
17+
scanf("%d",&f);
18+
c=bs(p,s,e,f);
19+
if(c==-1)
20+
{
21+
printf("THE ELEMENT IS NOT FOUND");
22+
}
23+
else
24+
{
25+
printf("THE ELEMENT %d IS FOUND AT POSITION %d\n",f,c);
26+
}
27+
return 0;
28+
}
29+
30+
int bs(int *a,int start,int end,int search)
31+
{
32+
int mid;
33+
mid=(start+end)/2;
34+
if(start>end)
35+
{
36+
return -1;
37+
}
38+
if(*(a+mid)==search)
39+
{
40+
return mid+1;
41+
}
42+
if(search<*(a+mid))
43+
{
44+
end=mid-1;
45+
bs(a,start,end,search);
46+
}
47+
else if(search>*(a+mid))
48+
{
49+
start=mid+1;
50+
bs(a,start,end,search);
51+
}
52+
}

0 commit comments

Comments
 (0)