Program to search an element using binary search - 100 Most Important C# Programs

100 Most Important C# Programs

55. Program to search an element using binary search

Code:

# include <stdio.h>

# include <conio.h>

main( )

{

int a[100],i,n,x, mid, top, bot,c;

clrscr();

printf(“enter the array size;”);

scanf(“%d”,&n);

printf(“enter the array elements”);

for(i=1;i<=n;i++)

scanf(“%d”,&a[i]);

top=1;

bot=n;

c=0;

printf(“enter the element to searched”);

scanf(“%d”,&x);

while((top <=bot)&&(c==0))

{

mid=(top+bot)/2;

if(a[mid]<x)

top=mid+1;

else

if(a[mid]>x)

bot=mid-1;

else

c=1;

}

if(c==1)

printf(“elements is at position;%d”,mid);

else

printf(“elements is not in list”);

getch( );

}