我创建了一个递归二进制搜索方法,它接收4个字段,数组,第一个元素,最后一个元素和searchLastName。在第二个if语句中,我试图将元素放在数组中间并将其与searchLastName进行比较。然后在else if语句中我试图比较它们并检查compareTo方法是否返回零或正数。我在使用if和else if语句时遇到了麻烦。
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);
}
答案 0 :(得分:1)
更改
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);
}
到
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);
}
编辑 - 正如cricket_007在其中一条评论中所指出的那样,尝试评估Math.floor((last-first)/2)
不会松散的预测。