Key points
- Calculate mid - int mid = low + (high - low) / 2; 
- if mid is lesser than target increase low by 1 or else mid is greater than target then high decrease by 1 
- the loop condition - low < = high 
 take ex : 1,3,5,7,9 target =9
 we have to track at point low == high so if its equal to target.
 
class Solution {
    public int search(int[] nums, int target) {
        int low=0;
        int high = nums.length-1;
        while(low<high){
            int mid = (low+high)/2;
            if(nums[mid]==target) return mid;
            else if(nums[mid]<target){
                low=mid+1;
            }
            else{
                high=mid-1;
            }
        }
        return -1;
    }
}
 

 
    
Top comments (0)