File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments