如何检索数组列表中的元素并进行比较?

时间:2016-11-19 17:51:35

标签: java recursion binary-search

我创建了一个递归二进制搜索方法,它接收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);
}

1 个答案:

答案 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)不会松散的预测。