Basic Binary Search

Basic Binary search code

class Solution {
public:
    int search(vector<int>& nums, int target) {
    
        int start = 0;
        int end = nums.size()-1;
        int mid,res=-1;
        
        while(start<=end){
            
            mid = (start+end)/2;
            
            if(nums[mid]==target){
                res = mid;
                break;
            }
            
            else if(nums[mid]<target){
                start = mid+1;
            }
            
            else{
                end = mid-1;
            }
        }
        
        return res;
     
    }
};

Last updated