Update Binary Search.cpp

This commit is contained in:
Faizan Ahamed 2020-04-26 14:46:20 +05:30 committed by GitHub
parent 2f6208532b
commit 9543e522f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,31 +1,31 @@
#include <iostream>
int binary_search(int a[], int l, int r, int key) {
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;
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;
}
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];
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)
std::cout << key << " found at index " << res << endl;
else
std::cout << key << " not found" << endl;
return 0;
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)
std::cout << key << " found at index " << res << endl;
else
std::cout << key << " not found" << endl;
return 0;
}