Danny Danny - 13 days ago 5
Java Question

How do I retrieve an element in an array list and compare it?

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

Answer

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.

Comments