-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.cpp
46 lines (46 loc) · 909 Bytes
/
BinarySearch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;
bool binarySearch(int *a, int size, int element)
{
int low = 0, high = size - 1, mid;
mid = (low + high) / 2;
while (low <= high)
{
if (a[mid] == element)
{
return true;
}
if (a[mid] < element)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return false;
}
int main()
{
int size, element;
cout << "Enter the size of the array: ";
cin >> size;
int *arr = new int[size];
cout << "Enter the elements: ";
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
cout << "Enter the element to be searched: ";
cin >> element;
if (binarySearch(arr, size, element))
{
cout << "Element found" << endl;
}
else
{
cout << "Element not found" << endl;
}
return 0;
}