Skip to content

Commit

Permalink
Merge pull request #680 from AvishkaWeebadde/AviW
Browse files Browse the repository at this point in the history
Binary search with a different approach of coding CPP
  • Loading branch information
keshavsingh4522 authored Oct 2, 2021
2 parents 9b92c0d + 4fee26a commit cb51a84
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 cb51a84

Please sign in to comment.