Skip to content

Commit 02bb478

Browse files
easy binary search program in cpp
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1
1 parent 173b314 commit 02bb478

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

binary-search.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
int search(vector<int>& nums, int target) {
4+
int beg=0;
5+
int n=nums.size();
6+
int end=n-1;
7+
while(beg<=end){
8+
int mid=(beg+end)/2;
9+
if (nums[mid]==target){
10+
return mid;
11+
}
12+
else if(nums[mid]>target){
13+
end=mid-1;
14+
}
15+
else if(nums[mid]<target){
16+
beg=mid+1;
17+
}
18+
}
19+
return -1;
20+
}
21+
};

0 commit comments

Comments
 (0)