-
Notifications
You must be signed in to change notification settings - Fork 72
/
binarySearch.cpp
56 lines (46 loc) · 804 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
47
48
49
50
51
52
53
54
55
56
#include <iostream>
using namespace std;
int binarySearch(int a[], int l, int r, int e)
{
while (l <= r)
{
int m = l + (r - l) / 2;
if (a[m] == e)
{
return m;
}
if (a[m] < e)
{
l = m + 1;
}
else
{
r = m - 1;
}
}
return -1;
}
int main(void)
{
int n, e;
cout<<"Enter number of elements in array:\n";
cin>>n;
cout<<"Enter elements in array:\n";
int a[n];
for(int i=0; i<n; i++)
{
cin>>a[i];
}
cout<<"Enter element to be found:\n";
cin>>e;
int found = binarySearch(a, 0, n - 1, e);
if(found == -1)
{
cout<<"Element not found!\n";
}
else
{
cout<<"Element found at position: "<<found+1<<"\n";
}
return 0;
}