Program To Implement Binary Search
Program To Implement Binary Search
IMPLEMENT
BINARY SEARCH
BY:
SHIPRANJALI
BCA-I(E)
WHAT IS BINARY SEARCH ?
#include<conio.h>
void main()
clrscr();
scanf("%d",&s);
printf("\nEnter %d elements:",s);
for(i=0;i<s;i++)
scanf("%d",&ar[i]);
}
printf("\nEnter the element to be search:");
scanf("%d",&item);
B=0;
E=s-1;
M=(B+E)/2;
while(B<=E)
{ if(ar[M]==item)
{ loc=M+1;
break;
}
else if(ar[M]<item)
B=M+1;
else
E=M-1;
M=(E+B)/2;
}
if(ar[M]==item)
printf(“\nElement %d is found and at location %d.",item,loc);
else
printf(“\nElement not found");
getch();
}
DEMONSTRATION:
3 6 7 11 32 33 53
[0] [1] [2] [3] [4] [5] [6]
3 6 7 11 32 33 53
B M E
B=0, E=s-1 and M=(E+B)/2
Is B<=E ? YES.
[0] [1] [2] [3] [4] [5] [6]
3 6 7 11 32 33 53
Is ar[M]=7 ? NO.
[0] [1] [2] [3] [4] [5] [6]
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
B M E Is B<=E ? YES.
[0] [1] [2] [3] [4] [5] [6]
3 6 7 11 32 33 53
Is ar[M]=7 ? NO.
[0] [1] [2] [3] [4] [5] [6]
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
Is ar[M]=7 ? YES.
Hence the item is found,
Searching complete.
OUTPUT: