TheAlgorithms-C-Plus-Plus/search/Binary Search.cpp

32 lines
683 B
C++
Raw Normal View History

2017-12-24 01:30:49 +08:00
#include <iostream>
2020-04-26 17:07:59 +08:00
int binary_search(int a[], int l, int r, int key) {
while (l <= r) {
2019-08-21 10:10:08 +08:00
int m = l + (r - l) / 2;
if (key == a[m])
2017-12-24 01:30:49 +08:00
return m;
2019-08-21 10:10:08 +08:00
else if (key < a[m])
r = m - 1;
2017-12-24 01:30:49 +08:00
else
2019-08-21 10:10:08 +08:00
l = m + 1;
2017-12-24 01:30:49 +08:00
}
return -1;
}
2020-04-26 17:07:59 +08:00
int main(int argc, char const *argv[]) {
2019-08-21 10:10:08 +08:00
int n, key;
2020-04-26 17:12:55 +08:00
std::cout << "Enter size of array: ";
std::cin >> n;
std::cout << "Enter array elements: ";
int* a = new int[n];
2020-04-26 17:07:59 +08:00
for (int i = 0; i < n; i++) {
2020-04-26 17:12:55 +08:00
std::cin >> a[i];
2017-12-24 01:30:49 +08:00
}
2020-04-26 17:12:55 +08:00
std::cout << "Enter search key: ";
std::cin >> key;
2019-08-21 10:10:08 +08:00
int res = binary_search(a, 0, n - 1, key);
if (res != -1)
2020-04-26 17:12:55 +08:00
std::cout << key << " found at index " << res << endl;
2017-12-24 01:30:49 +08:00
else
2020-04-26 17:12:55 +08:00
std::cout << key << " not found" << endl;
2017-12-24 01:30:49 +08:00
return 0;
}