condition : all the elements should be sorted order before when u want to find a element through binary search.
#include<stdio.h>
void binary(int *a,int,int,int);
main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int num;
printf("enter the searched num\n");
scanf("%d",&num);
binary(a,0,9,num);
}
void binary(int a[],int start,int end,int num)
{
int mid;
mid = (start+end)/2;
if(a[mid]==num)
{
printf("num z %d\n",a[mid]);
}
else if(a[mid]>num)
{
end = mid-1;
binary(a,start,end,num);
}
else if(a[mid]<num)
{
start = mid+1;
binary(a,start,end,num);
}
}
op :
enter the searched num
3
num z 3
----------------------------------------------------------------------------------------------------------------------
explanation :
1. binary(a,0,9,num);
2.binary (a=0xbfffdd20, start=0, end=9, num=3)
mid = (start+end)/2;
3.step
if(a[mid]==num)
print mid = 4
4.step
else if(a[mid]>num)
print a[mid] = 5
5.step
end = mid-1;
6.step
binary(a,start,end,num);
7.step
binary (a=0xbfffdd20, start=0, end=3, num=3) at binary.c:15
mid = (start+end)/2;
8.step
if(a[mid]==num)
print a[mid] = 2
9.step
else if(a[mid]>num)
print a[mid] = 2
10.step
else if(a[mid]<num)
print a[mid] = 2
11. step
start = mid+1;
12.step
binary(a,start,end,num);
13.step
binary (a=0xbfffdd20, start=2, end=3, num=3) at binary.c:15
mid = (start+end)/2;
14.step
if(a[mid]==num)
15.print a[mid] = 3
step
printf("num z %d\n",a[mid]);
16.print a[mid] = 3
0 comments: