binary search
#include <iostream>
using namespace std;
class bsearch1
{
private: int a[50], n, x;
public:
void binary();
};
void bsearch1::binary()
{
int i, j, temp, mid, beg, end;
beg = 0;
cout << "\n Enter size of array:";
cin >> n;
end = n - 1;
cout << "\n Enter n elements into array:";
for (i = 0; i < n; i++)
cin >> a[i];
//sort elements
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;}}}
cout << "\n Elements After Sorting Are:";
for (i = 0; i < n; i++)
cout<<a[i]<<"\t";
cout << "\n Enter search element:";
cin >> x;
while (beg <= end)
{
mid = (beg + end) / 2;
if (a[mid] == x)
{
cout << "\n Searching is successful and the element is present at " << (mid + 1) << " location";
return;
}
else if (x < a[mid])
end = mid - 1;
else
beg = mid + 1;
}
cout << "\n Search is unsuccessful"; }
int main() {
bsearch1 obj;
obj.binary();
return 0;
}