0

I stumbled on some issue in my codes, supposedly a return will stop my method but in my case isn't. I tried to make a method called "binarySearch" which supposedly do what its made to do.

public int binarySearch(int lowIndex, int highIndex, int[] arr, int val) {
    int middleIndex = (lowIndex + highIndex ) / 2;
    if(arr[middleIndex] < val) {
        lowIndex = middleIndex;
    } else if (arr[middleIndex] > val) {
        highIndex = middleIndex;
    } else {
        return middleIndex;
    }
    binarySearch(lowIndex, highIndex, arr, val);
    return 0;
}

the problem is if I already found the index where the search value reside else statement will return it and stop already. but instead, I always get "0", which is I think the value i set for default return return 0. so for some clarification, I added some text on my else statement to make sure it executed and return middleIndex, then the text showed up so basically my loop enters else statement and hopefully returned middleIndex but its not. maybe recursion has to do with this but I don't know maybe you guys can help me.

5
  • 6
    You don't return the result of your recursion. Commented Jul 11, 2018 at 4:31
  • i'm not familiar with recursion can you modify the codes to make it work? because i know i did return it through else statement and for what i know the recursion stops there hehe thx Commented Jul 11, 2018 at 4:34
  • You return it from your else, but then ignore it on this line: binarySearch(lowIndex, highIndex, arr, val); Commented Jul 11, 2018 at 4:36
  • binarySearch is calling itself with the same arguments that were passed to it. How is this ever producing anything other than an infinite loop and eventual stack overflow exception? Commented Jul 11, 2018 at 4:44
  • @KevinAnderson no it's not calling itself with the same arguments. It either returns the found index (else case) or modifies either lowIndex (if case) or the highIndex (else if case) before calling itself Commented Jul 11, 2018 at 5:02

5 Answers 5

1

Since the signature of your method says public int binarySearch, that means you should return the int from the recursive call of binarySearch method. You shouldn't really return 0 in a proper implementation of this method.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks mate, you explained whats wrong to my codes and did a hint how to do it. upvoting for that.
@YihangWang The risk you run when writing pretty much any recursive function in Java, it's unlikely to actually be a problem for the op.
0

You have to return the result of your recursion. You can refer to this code shown below to understand what you are doing wrong.

  // Returns index of x if it is present in arr[l..
    // r], else return -1
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r>=l)
        {
            int mid = l + (r - l)/2;

            // If the element is present at the 
            // middle itself
            if (arr[mid] == x)
               return mid;

            // If element is smaller than mid, then 
            // it can only be present in left subarray
            if (arr[mid] > x)
               return binarySearch(arr, l, mid-1, x);

            // Else the element can only be present
            // in right subarray
            return binarySearch(arr, mid+1, r, x);
        }

        // We reach here when element is not present
        //  in array
        return -1;
    }

For more information regarding BinarySearch and its implementation you can follow this link

2 Comments

thanks for the help mate but i can only choose 1 answer thanks by the way :)
Ofcourse you can choose the best answer. Upvote if it helped
0

Here is iterative java code for Binary Search, yours is somewhat flawed.

int binarySearch(int arr[], int x) {
    int l = 0, r = arr.length - 1;

    while (l <= r) {

        int m = l + (r-l)/2;

        if (arr[m] == x)
            return m;

        if (arr[m] < x)
            l = m + 1;

        else
            r = m - 1;
    }

    return -1;
}

1 Comment

thanks mate but swapnil explained whats wrong to my codes why i pick his answer, thanks by the way :)
0
 public static void binarySearch(int arr[], int first, int last, int key){  
   int mid = (first + last)/2;  
   while( first <= last ){  
      if ( arr[mid] < key ){  
        first = mid + 1;     
      }else if ( arr[mid] == key ){  
        System.out.println("Element is found at index: " + mid);  
        break;  
      }else{  
         last = mid - 1;  
      }  
      mid = (first + last)/2;  
   }  
   if ( first > last ){  
      System.out.println("Element is not found!");  
   }  

you can do it by recursion also.

Comments

0

There are minor mistakes in your code.

In recursion, when a function recursively calls itself, the function call should be placed in a return statement. This makes sure that the result of the recursive function calls is returned to calling function.

Here is the modified code -

class BinarySearch
{
    // Returns index of x if it is present in arr[l..
    // r], else return 0

    public int binarySearch(int lowIndex, int highIndex, int[] arr, int val) 
    {
        if(highIndex>=lowIndex)  //this line should be added for safety
        {
            int middleIndex = (lowIndex + highIndex ) / 2;
            if(arr[middleIndex] < val) 
            {
                lowIndex = middleIndex;
            } 
            else if (arr[middleIndex] > val) 
            {
                highIndex = middleIndex;
            } 
            else 
            {
                return middleIndex;
            }
            return binarySearch(lowIndex, highIndex, arr, val);  //this should be the return statement
        }
        return 0;
    }

    // Driver method to test above
    public static void main(String args[])
    {
        BinarySearch ob = new BinarySearch();
        int arr[] = {1,2,3,4,5,6,7,8};
        int n = arr.length;
        int x = 7;
        int result = ob.binarySearch(0,n-1,arr,x);
        if (result == 0)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index " + result);
    }
}

This code works fine.

Recursive stack explanation for the above code-

binarySearch(0,7,arr,val)

= return (binarySearch(3,7,arr,val))

= return (return (binarySearch(5,7,arr,val)))

= return (return (return 6)) //here 6 is the middleValue that is returned in else block

= return (return 6)

= return 6

Since, you didnt add the return statement in your code, your topmost function call in the recursive stack was returning 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.