forked from Kartikeya99/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.cpp
More file actions
44 lines (36 loc) · 955 Bytes
/
Copy pathbinarySearch.cpp
File metadata and controls
44 lines (36 loc) · 955 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
#include <iostream>
int binary_search(int a[], int r, int key) {
int l = 0;
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;
}
/** main function */
int main(int argc, char const* argv[]) {
int n, key;
std::cout << "Enter size of array: ";
std::cin >> n;
std::cout << "Enter array elements: ";
int* a = new int[n];
// this loop use for store value in Array
for (int i = 0; i < n; i++) {
std::cin >> a[i];
}
std::cout << "Enter search key: ";
std::cin >> key;
// this is use for find value in given array
int res = binary_search(a, n - 1, key);
if (res != -1)
std::cout << key << " found at index " << res << std::endl;
else
std::cout << key << " not found" << std::endl;
delete[] a;
return 0;
}