From 4fee26a3b212fa08aa9fd13498929d9fa48dbab2 Mon Sep 17 00:00:00 2001 From: AvishkaWeebadde Date: Sat, 2 Oct 2021 12:17:29 +0530 Subject: [PATCH] Binary search with a different approach of coding CPP --- CPP/binarySearch.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 CPP/binarySearch.cpp diff --git a/CPP/binarySearch.cpp b/CPP/binarySearch.cpp new file mode 100644 index 000000000..dbcd750ff --- /dev/null +++ b/CPP/binarySearch.cpp @@ -0,0 +1,32 @@ +#include +#include +using namespace std; + +class Solution { +public: + int search(vector& nums, int target) { + int k = 0; + int n = nums.size(); + for(int b = n / 2; b >= 1; b /= 2) + { + while(k+b < n && nums[k+b] <= target) + k += b; + } + + if (nums[k] == target) + { + return k; + } + + return -1; + } +}; + +int main() +{ + Solution s1; + //int t; + vector vec = {-1,0,3,5,9,12}; + cout << s1.search(vec, 9); + return 0; +} \ No newline at end of file