BINARY SEARCH by making functions and class in c++








Binary search by making class and functions


Binary search is faster and useful. you have to make a class and some related functions and take a binary search ..



#include<iostream>
using namespace std;
const int size = 10;
class array
{
private:
int a[size];
int n;
public:
array()
{
for (int i = 0; i<size; i++)
a[i] = 0;
n = 0;
}

void read()
{
int num;
cout<<"how many values you want to enter ?"<<endl;
cin>>num;
for(int i = 0; i<num; i++)
{
cout<<"Enter value:"<<endl;
cin>>a[i];
}
n = num;

}

void display()
{
for (int i = 0; i<n; i++)
cout<<a[i];
cout<<endl;
}

void search()
{
bool found = false;
int low = 0;
int high = n-1;
int key;
cout<<"enter key:"<<endl;
cin>>key;
while(low <= high && !found)
{
int mid = (low + high)/2;

if (key == a[mid])
found = true;
else if(key<a[mid])
high = mid - 1;
else
low = mid + 1;
}

if(found == true)
cout<<"Found"<<endl;
else
cout<<"not found"<<endl;
}

};

void main()
{
array arr1, arr2;
arr1.read();
cout<<"the entered array is : "<<endl;
arr1.display();
arr1.search();
}