Binary Search
#include <iostream>
using namespace std;
//binary search
int main()
{
int a[50], n, i, j, mid, elem, low, high, flag = 0;
cout << "Enter the number of element in array: " << endl;
cin >> n;
cout << "Enter the element: " << endl;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
cout << "Enter the element to be found" << endl;
cin >> elem;
// selection sort
int min;
for (int i = 1; i <= n - 1; i++)
{
min = i;
for (int j = i + 1; j <= n; j++)
{
if (a[min] > a[j])
min = j;
}
int temp = a[min];
a[min] = a[i];
a[i] = temp;
}
cout << "Array after sorting: " << endl;
for (int i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
low = 0;
high = n;
while (low <= high)
{
mid = (low + high) / 2;
if (elem == a[mid])
{
cout << "\nElement is found at index " << mid << endl;
return 0;
}
else if (elem > a[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
cout << "Element is not present!! " << endl;
}