Wednesday, 4 September 2013

BINARY SEARCH C PROGRAM


/*CSEMATTER.BLOGSPOT.IN

Program: Program in C to perform binary search*/

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[20],num,count,mid,beg,end,term,found=0;
clrscr();
printf("enter the no. of elements to enter");
scanf("%d",&num);
printf("enter the numbers");
for(count=0;count<num;count++)
{scanf("%d",&arr[count]);}
printf("enter the term to be searched");
scanf("%d",&term);
beg=0;
end=num;
mid=(beg+end)/2;
while(beg<=end)
{
mid=(beg+end)/2;
if(term<arr[mid])
{end=mid-1;
}
if(term>arr[mid])
{
beg=mid+1;
}
if(term==arr[mid])
{
printf("element found at %d position in array",mid+1);
found=1;
break;
}
}
if(found==0)
{
printf("term not found");
}
getch();
}

/*OUTPUT:
enter the no. of elements to enter 6
enter the numbers
10
42
48
56
78
99
enter the term to be searched 48
element found at 3 position in array*/

No comments:

Post a Comment