diff --git a/Search/C++/Binary_Search/BinarySearch.cpp b/Search/C++/Binary_Search/BinarySearch.cpp new file mode 100644 index 0000000..15ee97e --- /dev/null +++ b/Search/C++/Binary_Search/BinarySearch.cpp @@ -0,0 +1,38 @@ +#include +#include + +using namespace std; + +int binary_search(vector &numbers, int value) +{ + int left = 0, right = numbers.size() - 1; + while(left <= right) { + int i = (left + (right - left) / 2); + if (numbers[i] == value) { + return i; + } + if (numbers[i] < value) { + left = i + 1; + }else { + right = i -1; + } + } + return -1; + +} + +int main() { + + vector nums{1,2,3,4,5,6,7,8,9,10}; + vector values{2, 4, 20}; + + for (int val : values) { + int index = binary_search(nums, val); + if (index != -1) { + cout << "Value " << val << " exists in index " << index << endl; + } else { + cout << "Value " << val << " does not exist." << endl; + } + } + +} \ No newline at end of file diff --git a/Search/C++/Binary_Search/ReadMe.md b/Search/C++/Binary_Search/ReadMe.md new file mode 100644 index 0000000..2b4ac67 --- /dev/null +++ b/Search/C++/Binary_Search/ReadMe.md @@ -0,0 +1,7 @@ +# Binary Search algorithm implementation in C== + +Time complexity - O( Log(n) ) +Space Complexity - O(1) + + +[Algorithm Explanation](https://www.geeksforgeeks.org/binary-search/)