Skip to content

Commit e505883

Browse files
authored
Create binary_search.cpp
1 parent 2deb25a commit e505883

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

searches/binary_search.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Binary Search implemented in C++
2+
// Carlos Abraham Hernandez
3+
// algorithms.abranhe.com/searches/binary-search
4+
// repl.it/@abranhe/Binary-Search
5+
6+
#include <iostream>
7+
using namespace std;
8+
9+
int binary_search(int a[],int l,int r,int key)
10+
{
11+
while(l<=r)
12+
{
13+
int m = l + (r-l) / 2;
14+
15+
if(key == a[m])
16+
return m;
17+
else if(key < a[m])
18+
r = m-1;
19+
else
20+
l = m+1;
21+
}
22+
return -1;
23+
}
24+
25+
int main(int argc, char const *argv[])
26+
{
27+
int n, key;
28+
cout << "Enter size of array: ";
29+
cin >> n;
30+
cout << "Enter array elements: ";
31+
int a[n];
32+
33+
for (int i = 0; i < n; ++i)
34+
{
35+
cin>>a[i];
36+
}
37+
cout << "Enter search key: ";
38+
cin>>key;
39+
40+
int res = binary_search(a, 0, n-1, key);
41+
42+
if(res != -1)
43+
cout<< key << " found at index " << res << endl;
44+
else
45+
cout << key << " not found" << endl;
46+
return 0;
47+
}

0 commit comments

Comments
 (0)