DEV Community

Sudeep .U
Sudeep .U

Posted on

Binary Search

Key points

  1. Calculate mid - int mid = low + (high - low) / 2;

  2. if mid is lesser than target increase low by 1 or else mid is greater than target then high decrease by 1

  3. 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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)