-
Notifications
You must be signed in to change notification settings - Fork 4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Binary search with a different approach of coding CPP
- Loading branch information
1 parent
a61c4f4
commit 4fee26a
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |