C++ program for binary search. - coderforcoders

Search

Wednesday, 13 March 2019

C++ program for binary search.

#include<iostream>
using namespace std;
class binarySearch{
public:
int size,array[100],first,last,middle;
void search(int number)
{
first=0;
last=size-1;
middle=(first+last)/2;
while(first<=last)
{
 
if(array[middle]==number)
    {
cout<<"Number found at location "<<middle+1<<"\n";
break;
    }
else if(number>array[middle])
  {

   first=middle+1;

   }
else
    {
last=middle-1;
    }

middle=(first+last)/2;

}
if(first > last)
{
cout<<"Number not found\n";


}
}
};
int main()
{
binarySearch obj1;
        int number,i;
cout<<"Please enter the size of array\n";
cin>>obj1.size;

cout<<"Please enter the element\n";
for(i=0;i<obj1.size;i++)
cin>>obj1.array[i];

cout<<"eneter the element that you want to search\n";
cin>>number;

obj1.search(number);


return 0;
}


Output :


No comments:

Post a Comment