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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay