TheAlgorithms-C-Plus-Plus/search/binary_search.cpp

57 lines
1.2 KiB
C++
Raw Normal View History

2020-05-29 07:37:33 +08:00
/**
* @file
* @brief [Binary search
* algorithm](https://en.wikipedia.org/wiki/Binary_search_algorithm)
*/
2017-12-24 01:30:49 +08:00
#include <iostream>
2020-05-29 07:37:33 +08:00
/** binary_search function
* \param [in] a array to sort
* \param [in] r right hand limit = \f$n-1\f$
* \param [in] key value to find
* \returns index if T is found
* \return -1 if T is not found
*/
int binary_search(int a[], int r, int key) {
int l = 0;
2020-04-27 12:51:11 +08:00
while (l <= r) {
2020-05-29 07:37:33 +08:00
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 */
2020-04-26 17:24:26 +08:00
int main(int argc, char const* argv[]) {
2020-04-27 12:51:11 +08:00
int n, key;
std::cout << "Enter size of array: ";
std::cin >> n;
std::cout << "Enter array elements: ";
2020-05-29 07:37:33 +08:00
2020-04-27 12:51:11 +08:00
int* a = new int[n];
2020-05-29 07:37:33 +08:00
// this loop use for store value in Array
2020-04-27 12:51:11 +08:00
for (int i = 0; i < n; i++) {
std::cin >> a[i];
2020-05-29 07:37:33 +08:00
}
2020-04-27 12:51:11 +08:00
std::cout << "Enter search key: ";
std::cin >> key;
2020-05-29 07:37:33 +08:00
// this is use for find value in given array
int res = binary_search(a, n - 1, key);
2020-04-27 12:51:11 +08:00
if (res != -1)
2020-05-29 07:37:33 +08:00
std::cout << key << " found at index " << res << std::endl;
2020-04-27 12:51:11 +08:00
else
2020-05-29 07:37:33 +08:00
std::cout << key << " not found" << std::endl;
delete[] a;
2020-04-27 12:51:11 +08:00
return 0;
}