Social Icons

Friday, 7 March 2014

Program of Binary search in 1D Array

#include<conio.h>
#include<stdio.h>

main()
{
int search(int [],int,int);
int n,i,a[100],e,res;
clrscr();
printf(" How Many Elements you want to enter : ");
scanf("%d",&n);
printf("\n Enter Elements of Array in Accending order\n");

/* otherwise we have to sort the elements using any sorting.*/

for(i=0;i<n;++i)
{
scanf("%d",&a[i]);
}

printf("\n Enter element to search : ");
scanf("%d",&e);
res=search(a,n,e);
if(res!=0)
printf("\n Element is Found at position : %d",res+1);
else
printf("\n Element is not found...");
getch();
}

int search(int a[],int n,int e)
{
int f,l,m;
f=0;
l=n-1;
while(f<=l)
{
m=(f+l)/2;
if(e==a[m])
return(m);
else
if(e>a[m])
f=m+1;
else
l=m-1;
}
return 0;
}

    
                                                          Output

No comments:

Post a Comment