1

I've created a recursive binary search method that takes in 4 fields, the array, the first element, last element, and searchLastName. In the second if statement i'm trying to get the element in the middle of array and compare it to searchLastName. Then in the else if statement i'm trying to compare them and checking to see if the compareTo method returns zero or a positive number. I'm having trouble with both the if and the else if statement.

private static int binarySearch(ArrayList<Member> list, int firstElem, int lastElem, String searchLastName)
{
    int middle;

    if( firstElem > lastElem )
        return -1;

    middle = ( firstElem + lastElem ) / 2;

    if( list.get(middle).getLastName.equals(searchLastName) )
        return middle;
    else if( list.get(middle).getLastName.compareTo(searchLastName) >= 0 )
        return binarySearch(list, middle + 1, lastElem, searchLastName);
    else
        return binarySearch(list, firstElem, middle - 1, searchLastName);
}
Danny
  • 169
  • 1
  • 1
  • 10
  • 2
    What is the desired output? What happens now? – Murat Karagöz Nov 19 '16 at 17:54
  • 1
    [Your `middle` calculation is wrong](https://stackoverflow.com/questions/4064094/calculate-midpoint) – OneCricketeer Nov 19 '16 at 17:59
  • @MuratK. It would be the position of searchLastName which would be the lastname that's being passed. At the moment it's giving mean error for .getLastName on both lines saying it cannot find symbol but the .getLastName is already created in another class – Danny Nov 19 '16 at 17:59
  • `getLastName` vs `getLastName()`?? – OneCricketeer Nov 19 '16 at 17:59
  • Maybe its trying to find the variable named `getLastName` instead of function. Can you change it to `getLastName()` – Kishore Bandi Nov 19 '16 at 18:01
  • @cricket_007Honestly the most simple mistakes get through sometimes and you never notice them. Thank you a million times over. – Danny Nov 19 '16 at 18:02

1 Answers1

1

change

if( list.get(middle).getLastName.equals(searchLastName) )
        return middle;
else if( list.get(middle).getLastName.compareTo(searchLastName) >= 0 )
        return binarySearch(list, middle + 1, lastElem, searchLastName);
else
        return binarySearch(list, firstElem, middle - 1, searchLastName);
}

to

if( list.get(middle).getLastName().equals(searchLastName) )
        return middle; //should be ideally a getter for lastName
else if( list.get(middle).getLastName().compareTo(searchLastName) >0 ) //equals already checked, not requied here
        return binarySearch(list, middle + 1, lastElem, searchLastName);
else
        return binarySearch(list, firstElem, middle - 1, searchLastName);
}

Edit - Also as pointed out by cricket_007 in one of the comments try evaluating the Math.floor((last-first)/2) to not loose precission.

Naman
  • 27,789
  • 26
  • 218
  • 353