+ 3
// corrected code
#include<iostream>
using namespace std; // include namespace
int Bsearch(int[],int,int);
int main()
{
int AR[50],ITEM, N, index;
cout<<"Enter desired array size(max. 50)...";
cin>>N;
cout<<"\nEnter Array elements(must be sorted in Asc order)\n";
for(int i=0; i<N;i++)
{
cin>>AR[i];
}
cout<<"\nEnter Element to be searched for...";
cin>>ITEM;
index=Bsearch(AR,N,ITEM);
if(index==-1)
cout<<"\nSorry!!! Given Element could not be found.\n";
else
cout<<"\nElement found at index:"<<index<<",position:"<<index+1<<endl;
}
int Bsearch(int AR[],int size,int item) //function to perform binary search
{
int beg,last,mid;
beg=0; last=size-1;
while(beg+ last)
{
mid = (beg+last)/2;
if (item == AR[mid])
return mid;
else if (item>AR[mid])
beg=mid+1;
else
last=mid-1;
}
return -1; // the control will reach here only when item isnt found
}
+ 2
/*
read comments
#include<iostream.h> // cpp file dont have .h extention, invalid header, remove .h
#include<conio.h> // deprecated header, remove
int Bsearch(int[],int,int);
void main() // must be int main()
{ int AR[50],ITEM, N, index;
clrscr(); // remove it here dont work.
cout<<"Enter desired array size(max. 50)...";
cin>>N;
cout<<"\nEnter Array elements(must be sorted in Asc order)\n";
for(int i=0; i<N;i++)
{ cin>>A R[i]; } // sholud not have a space between variables..
*/