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

32 lines
621 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) {
2020-04-26 17:16:20 +08:00
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;
2017-12-24 01:30:49 +08:00
}
2020-04-26 17:19:01 +08:00
int main() {
2020-04-26 17:16:20 +08:00
int n, key;
std::cout << "Enter size of array: ";
std::cin >> n;
std::cout << "Enter array elements: ";
int* a = new int[n];
for (int i = 0; i < n; i++) {
std::cin >> a[i];
}
std::cout << "Enter search key: ";
std::cin >> key;
int res = binary_search(a, 0, n - 1, key);
if (res != -1)
2020-04-26 17:19:01 +08:00
std::cout << key << " found at index " << res << std::endl;
2020-04-26 17:16:20 +08:00
else
std::cout << key << " not found" << endl;
return 0;
}