MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / search

Method search

C++/BinarySearch.cpp:9–29  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7class Solution {
8public:
9 int search(vector<int>& nums, int target) {
10
11 int si=0, ei=nums.size()-1;
12
13 while(si <= ei) {
14 // index of the middle element
15 int mid = si + (ei-si)/2;
16
17 // found target element
18 if(nums[mid] == target) {
19 return mid;
20 } else if(nums[mid] < target) { // target on right side of middle element
21 si += 1;
22 } else { // target on left side of middle element
23 ei -= 1;
24 }
25 }
26
27 // target element not present in given array
28 return -1;
29 }
30};
31
32// Time Complexity: O(log(n))

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected