diff --git a/DIRECTORY.md b/DIRECTORY.md index b35ff9991..bf04997f0 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -162,7 +162,7 @@ * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segTree.cpp) ## Search - * [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Binary%20Search.cpp) + * [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/binary_search.cpp) * [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/exponential_search.cpp) * [Hash Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/hash_search.cpp) * [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Interpolation%20Search.cpp) diff --git a/search/Binary Search.cpp b/search/Binary Search.cpp deleted file mode 100644 index 2e90855e8..000000000 --- a/search/Binary Search.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include -using namespace std; -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; -} -int main(int argc, char const *argv[]) -{ - int n, key; - cout << "Enter size of array: "; - cin >> n; - cout << "Enter array elements: "; - int a[n]; - for (int i = 0; i < n; ++i) - { - cin >> a[i]; - } - cout << "Enter search key: "; - cin >> key; - int res = binary_search(a, 0, n - 1, key); - if (res != -1) - cout << key << " found at index " << res << endl; - else - cout << key << " not found" << endl; - return 0; -} \ No newline at end of file diff --git a/search/binary_search.cpp b/search/binary_search.cpp new file mode 100644 index 000000000..9933c9816 --- /dev/null +++ b/search/binary_search.cpp @@ -0,0 +1,34 @@ +#include +// binary_search function +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; + } +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]; +// this loop use for store value in Array + for (int i = 0; i < n; i++) { + std::cin >> a[i]; + } + std::cout << "Enter search key: "; + std::cin >> key; +// this is use for find value in given array + int res = binary_search(a, 0, n - 1, key); + if (res != -1) + std::cout << key << " found at index " << res << std::endl; + else + std::cout << key << " not found" << std::endl; + return 0; +}