DEV Community

Cover image for Binary Search: Recursive and Iterative method
Swapnil Gupta
Swapnil Gupta

Posted on

Binary Search: Recursive and Iterative method

LeetCode discussion


class Solution {

    // iterative
    public int search(int[] nums, int target) {

        // Corner case
        if(nums == null || nums.length == 0) return -1;

        int low = 0;
        int high = nums.length-1;

        while(low <= high){
            int mid = (high-low)/2 + low;
            if(nums[mid] == target) return mid;
            if(nums[mid] < target) low = mid + 1;
            else high = mid  - 1;
        }
        return -1;
    }

    // Recursive 
    public static int Rsearch(int[] nums, int low, int high, int target){

        if(low > high) return -1;

        int mid = low + (high-low)/2;
        if(target == nums[mid])
            return mid;
        else if(target < nums[mid])
            return Rsearch(nums, low, mid-1, target);
        else
            return Rsearch(nums, mid+1, high, target);
    }
}
Enter fullscreen mode Exit fullscreen mode

A good blog to read about binary Search callicoder

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay