mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
document binary search
This commit is contained in:
parent
186c7a2de8
commit
94f3ffe146
@ -1,35 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* @file
|
||||||
|
* @brief [Binary search
|
||||||
|
* algorithm](https://en.wikipedia.org/wiki/Binary_search_algorithm)
|
||||||
|
*/
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
// binary_search function
|
|
||||||
int binary_search(int a[], int l, int r, int key) {
|
/** 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;
|
||||||
|
|
||||||
while (l <= r) {
|
while (l <= r) {
|
||||||
int m = l + (r - l) / 2;
|
int m = l + (r - l) / 2;
|
||||||
if (key == a[m])
|
if (key == a[m])
|
||||||
return m;
|
return m;
|
||||||
else if (key < a[m])
|
else if (key < a[m])
|
||||||
r = m - 1;
|
r = m - 1;
|
||||||
else
|
else
|
||||||
l = m + 1;
|
l = m + 1;
|
||||||
}
|
}
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** main function */
|
||||||
int main(int argc, char const* argv[]) {
|
int main(int argc, char const* argv[]) {
|
||||||
int n, key;
|
int n, key;
|
||||||
std::cout << "Enter size of array: ";
|
std::cout << "Enter size of array: ";
|
||||||
std::cin >> n;
|
std::cin >> n;
|
||||||
std::cout << "Enter array elements: ";
|
std::cout << "Enter array elements: ";
|
||||||
|
|
||||||
int* a = new int[n];
|
int* a = new int[n];
|
||||||
// this loop use for store value in Array
|
|
||||||
|
// this loop use for store value in Array
|
||||||
for (int i = 0; i < n; i++) {
|
for (int i = 0; i < n; i++) {
|
||||||
std::cin >> a[i];
|
std::cin >> a[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Enter search key: ";
|
std::cout << "Enter search key: ";
|
||||||
std::cin >> key;
|
std::cin >> key;
|
||||||
// this is use for find value in given array
|
|
||||||
int res = binary_search(a, 0, n - 1, key);
|
// this is use for find value in given array
|
||||||
|
int res = binary_search(a, n - 1, key);
|
||||||
if (res != -1)
|
if (res != -1)
|
||||||
std::cout << key << " found at index " << res << std::endl;
|
std::cout << key << " found at index " << res << std::endl;
|
||||||
else
|
else
|
||||||
std::cout << key << " not found" << std::endl;
|
std::cout << key << " not found" << std::endl;
|
||||||
|
|
||||||
delete[] a;
|
delete[] a;
|
||||||
return 0;
|
return 0;
|
||||||
|
Loading…
Reference in New Issue
Block a user