Tuesday, July 26, 2011

Binary Search in C

#include
void binary()
{
int i,item,mid;
int list[6];
printf("Enter the values:");
for(i=0;i<5;i++)
{
scanf("%d",&list[i]);
}
printf("Entered Items are:");
for(i=0;i<5;i++)
{
printf("%d ",list[i]);
}
printf("\n");
//int list[5]={1,2,3,4,5};
int lower,upper;
lower=0;
upper=4;
printf("item to be searched:");
scanf("%d",&item);
while(1)
{
mid=(lower+upper)/2;
if(list[mid]==item)
{
printf("position of item is:");
printf("%d",mid+1);
return;
}
else if(list[mid] {
lower=mid+1;
}
else
{
upper=mid-1;
}
if(lower>upper)
{
printf("item does not exist:");
return;
}


}



}
int main()
{
binary();
}

No comments:

Post a Comment

Search This Blog