WAP in C to search an element in an array using binary search?

#include<stdio.h>
#include<conio.h>
#define N 100
int main()
{
int a[N],n,i,num,ub,lb=0,mid,flag=0;
clrscr();
printf(“\nEnter the size of array”);
scanf(“%d”,&n);
printf(“Enter the element of array”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“\nEntered the searched element”);
scanf(“%d”,&num);
ub=(n-1);
while(lb<=ub)
{
mid=(ub+lb)/2;
if(a[mid]==num)
{
flag=1;
break;
}
else if(num<a[mid]) ub=(mid-1); else if(num>a[mid])
lb=(mid+1);
}
if(flag==1)
printf(“\nNumber is present”);
else
printf(“\nNumber is not present”);
getch();
return(0);
}

Output :-

binarysearchbinarysearch1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s