In: Computer Science
Write a program of Binary Search in C++ by using function and arrays with the explanation.
#include<iostream>
using namespace std;
int main()
{
int BSearch(int [],int,int); //declaring a BSearch()_to
search position of given element
int N,i,A[50],E,X;
cout<<"Enter number of elements:"; //input size of
array
cin>>N;
cout<<"\nEnter elements\n"; //input elements of
array
for(i=0;i<N;++i)
{
cin>>A[i];
}
cout<<"\nElement to search:"; //input element to
earch
cin>>E;
X=BSearch(A,N,E); // initialize the value of function to
variable X
if(X!=-1) //IF VALUE OF x IS NOT -1 THEN PRINT THIS
STATEMENT
cout<<"\n Position of element is "<<X+1;
else
cout<<"\nNo element found!";
return 0;
}
int BSearch(int A[],int N,int E) // Function to search
element ina array
{
int Fst,Lst,Mid; // Taking variable Fst(First position
),Lst(Last position) and Mid(Middle of array)
Fst=0; Lst=N-1;
while(Fst<=Lst) // execute the loop when value of First
is lessthen last
{
Mid=(Fst+Lst)/2; // Finding the middle of
array
if(E==A[Mid]) //if element is equal to value of element at
position Mid
return(Mid); // return the value to X
else
if(E>A[Mid]) // if element is greater element at positon
mid
Fst=Mid+1; // then the value of First will be Middle +1 and
last will be same and search again between this
position
else
Lst=Mid-1;
}
return -1;
}