Skip to content

Commit

Permalink
Binary search with a different approach of coding CPP
Browse files Browse the repository at this point in the history
  • Loading branch information
AvishkaWeebadde committed Oct 2, 2021
1 parent a61c4f4 commit 4fee26a
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions CPP/binarySearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
int search(vector<int>& 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<int> vec = {-1,0,3,5,9,12};
cout << s1.search(vec, 9);
return 0;
}

0 comments on commit 4fee26a

Please sign in to comment.