Results 1 to 2 of 2
  1. #1
    marsluo is offline Member
    Join Date
    Apr 2011
    Posts
    3
    Rep Power
    0

    Default return in recursion

    The following code is a simple recursive binary search method that is supposed to return the index of the first match in an array, or -1 while no match. The test case result shows that no matter what if-then case it jumps to, it returns only 0, which I think, is from the very last statement. But, that statement can't be removed, otherwise "no return" error occurs. Would anyone help figure this out? Thanks



    public int findLocation(int[] anArray, int aTarget, int lowIndex, int highIndex){

    if(lowIndex>highIndex){
    System.out.println("can't find it!");

    return -1;
    }

    Mid=(int) (lowIndex+highIndex)/2;

    if(anArray[Mid]==aTarget){
    System.out.println("There is a match!");
    return Mid;

    }


    if(anArray[Mid]<aTarget){
    lowIndex=Mid+1;
    findLocation(anArray, aTarget, lowIndex, highIndex);
    }
    else if(anArray[Mid]>aTarget){
    highIndex=Mid-1;
    findLocation(anArray, aTarget, lowIndex, highIndex);
    }

    return 0;

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    This is not "advanced java", but more importantly it is a double post which is not fair to the volunteers of this forum as it needlessly splits the discussion. Locking this thread and deleting soon. OP, please no more double posting questions.

Similar Threads

  1. Return values and Recursion
    By blug in forum New To Java
    Replies: 4
    Last Post: 11-14-2010, 12:55 PM
  2. recursion and tail-recursion differences
    By OptimusPrime in forum New To Java
    Replies: 2
    Last Post: 12-28-2009, 06:26 PM
  3. Help with Recursion and return statement
    By nicolek808 in forum New To Java
    Replies: 3
    Last Post: 09-10-2009, 10:02 AM
  4. Recursion
    By Mika in forum New To Java
    Replies: 5
    Last Post: 01-04-2009, 01:13 AM
  5. recursion
    By ravian in forum New To Java
    Replies: 2
    Last Post: 12-03-2007, 05:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •