我一直在尝试进行二进制搜索,以搜索排序的单词列表。我有点麻烦,因为它可以找到一些单词,但其他单词返回-1。
这是我的二进制搜索代码:
public static int binarySearch(List <String> sortedAL, String key, int lowIndex, int highIndex)
{
int middle = (lowIndex + highIndex) / 2;
if(highIndex < lowIndex)
{
//System.out.println(-1);
return -1;
}
if(key.equalsIgnoreCase(sortedAL.get(middle)))
{
return middle;
}
/*
str1.compareTo(str2)
* if s1 > s2, it returns positive number
* if s1 < s2, it returns negative number
* if s1 == s2, it returns 0
*/
else if(key.compareToIgnoreCase(sortedAL.get(middle)) < 0)
{
return binarySearch(sortedAL, key, lowIndex, middle - 1);
}
else
{
return binarySearch(sortedAL, key, middle + 1, highIndex);
}
}