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

Top comments (0)

Build Anything...


Use any Linode offering to create something for the DEV x Linode Hackathon 2022. A variety of prizes are up for grabs, inculding $1,000 USD. 👀

→ Join the Hackathon <-