Quote:
|
Originally Posted by karmanya
#include <iostream.h>
int main ()
{
int a[10],n,x,pos=-1,i,first,last,mid;
cout<<" Enter the number of elements into the array ";
cin>>n;
for(i=0;i<n;++i)
{
cout<<"\n Enter element number "<<i+1<<" ";
cin>>a[i];
}
cout<<"Enter the number to be searched \t";
cin>>x;
first=0;
last=n-1;
while((first<=last)&&(pos==-1))
{
mid=(first+last)/2;
if(a[mid]==x)
pos=mid;
else
last=mid-1;
}
if(pos==-1)
cout<<" \t Element not found ";
else
cout<<" Element found at position "<<pos+1;
return 0;
}
|
AFAIK, the logic is wrong mate...
Binary search should divide the array of elements into 2 and then find out which half the element is likely to be found..{assuming the array is sorted } and then narrow the search down to that particular half ...
the code you've posted doesn't do that..
it should be something like :
if ( element to be searched ) < the middle element,
then search the array from first element to an element before middle element
else
search the array from the element after the middle element to the last element
all this should be done within a conditional loop, ofcourse.
PS : it was soo tempting to write the code itself... but i guess you'd want to do it on your own ...