Sunday, 5 October 2014

BINARY SEARCH

/*binary search*/
#include<iostream.h>
#include<conio.h>                 /*for clrscr hadder file*/
#include<stdlib.h>
void main()
{
clrscr();
int ar[10],value,size,i,flag,lower,middle,upper;
char choice;
cout<<"Enter the size ";
cin>>size;
cout<<"Enter the array\n";
for(i=1;i<=size;i++)
cin>>ar[i];
do{
flag=0;
cout<<"\nEnter search element ";
cin>>value;
lower=1;
upper=size;
while(lower<upper)
{
middle=(lower+upper)/2;
if(value>ar[middle])
lower=middle;
if(value<ar[middle])
upper=middle;

if(value==ar[middle])
{
cout<<"\nElement found ";
cout<<"Element postion "<<middle;
flag=1;
break;
}
 /*search start*/
}

No comments:

Post a Comment