EmbLogic's Blog

A program For Binary Search

#include<stdio.h>
int main()
{
int i,j,n,temp,search,low,high,mid,c;
printf(“Enter the element of array \n “);
scanf(“%d”,&n);
int a[n];
printf(“Enter the element\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf(“Array After Shorting\n”);
for(i=0;i<n;i++)
{
printf(“a[%d]=%d\n”,i,a[i]);
}
printf(“Enter the Number To be Search :\n”);
scanf(“%d”,&search);
low=0;
high=n-1;
while(1)
{
mid=(high+low)/2;
if(search==a[mid])
{
printf(“%d is found %dth location \n”,search,mid);
break;
}
else if(search>a[mid])
{
low=mid+1;
high=n-1;
}
else if(search<a[mid])
{
low=0;
high=mid-1;
}
else if(low>high)
{
printf(“%d is not found\n”,search);
break;
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>