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);
            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)

Join us at DEV
Yes, this is technically an “ad”, but really we just want to ask if you want to join DEV. We have 900k+ developers reading, posting, and enjoying community, and would love to have you.   Create an account and continue your coding journey.