forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
47 lines (40 loc) · 796 Bytes
/
binary_search.cpp
File metadata and controls
47 lines (40 loc) · 796 Bytes
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
// Binary Search implemented in C++
// Carlos Abraham Hernandez
// algorithms.abranhe.com/searches/binary-search
// repl.it/@abranhe/Binary-Search
#include <iostream>
using namespace std;
int binary_search(int a[],int l,int r,int key)
{
while(l<=r)
{
int m = l + (r-l) / 2;
if(key == a[m])
return m;
else if(key < a[m])
r = m-1;
else
l = m+1;
}
return -1;
}
int main(int argc, char const *argv[])
{
int n, key;
cout << "Enter size of array: ";
cin >> n;
cout << "Enter array elements: ";
int a[n];
for (int i = 0; i < n; ++i)
{
cin>>a[i];
}
cout << "Enter search key: ";
cin>>key;
int res = binary_search(a, 0, n-1, key);
if(res != -1)
cout<< key << " found at index " << res << endl;
else
cout << key << " not found" << endl;
return 0;
}