From 7f00108f421ef47899714856c67c43859de0204e Mon Sep 17 00:00:00 2001 From: jenyyy4 Date: Wed, 30 Oct 2024 15:16:56 +0530 Subject: [PATCH] added binarySearch.cpp --- C++/binarySearch.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/binarySearch.cpp diff --git a/C++/binarySearch.cpp b/C++/binarySearch.cpp new file mode 100644 index 0000000..c95fa3c --- /dev/null +++ b/C++/binarySearch.cpp @@ -0,0 +1,35 @@ +#include +#include + +int binarySearch(const std::vector& arr, int target) { + int left = 0; + int right = arr.size() - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + if (arr[mid] == target) { + return mid; + } else if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return -1; +} + +int main() { + std::vector arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + int target = 5; + + int result = binarySearch(arr, target); + + if (result != -1) { + std::cout << "Element found at index " << result << std::endl; + } else { + std::cout << "Element not found" << std::endl; + } + + return 0; +}