From cdd9ee484e7dc2f982fe7283e360cb9c0197c20d Mon Sep 17 00:00:00 2001 From: Mohammad khan Date: Tue, 24 Oct 2023 14:15:44 +0530 Subject: [PATCH] Added BinarySearch --- BinarySearch.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 BinarySearch.cpp diff --git a/BinarySearch.cpp b/BinarySearch.cpp new file mode 100644 index 0000000..a65e329 --- /dev/null +++ b/BinarySearch.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int search(vector& nums, int target) { + int n = nums.size(); //size of the array + int low = 0, high = n - 1; + + // Perform the steps: + while (low <= high) { + int mid = (low + high) / 2; + if (nums[mid] == target) return mid; + else if (target > nums[mid]) low = mid + 1; + else high = mid - 1; + } + return -1; + } +}; \ No newline at end of file