递归二进制搜索Java

时间:2015-02-12 02:21:31

标签: java recursion binary-search-tree

我有一个名为sArray的arraylist,其中包含大量拼写正确的单词。我需要向这个递归二进制搜索方法(密钥)发送一个单词,并确定它是否拼写正确。我理解递归二进制搜索是如何工作的但是我不知道如何确定我是否需要向左或向右搜索带有关键字的sArray,因为我正在处理字符串而不是整数。

 public int bSearch(String key, int lowIndex, int highIndex) {

    if (lowIndex > highIndex) {
        System.out.print("The word is incorrect");
        return -1;
    }

    mid = (lowIndex + highIndex) / 2;
    if (sArray.get(mid).equals(key)) {
        return mid;
    } else if (key < sArray.get(mid)) {
        return bSearch(key, lowIndex, mid - 1);
    } else {
        return bSearch(key, mid + 1, highIndex);
    }
}

2 个答案:

答案 0 :(得分:0)

您可以轻松地将字符串与整数进行比较:

if (testString.compareTo(key) < 0) {
    ...
} else if (testString.compareTo(key) > 0) {
    ...
} else {
    ...
}

答案 1 :(得分:0)

compareTo方法允许您比较实现Comparable接口的任何对象。由于String类实现了Comparable接口,因此compareTo将在您的方法中起作用。

使用compareTo时要记住的一个方便的技巧是将其视为减法:

a.compareTo(b)如果a-b导致否定答案,则返回-1。 (a在订购时出现在b之前)

如果a - b导致肯定答案,则a.compareTo(b)将返回1。 (a在订购时出现在b之后)

a.compareTo(b)如果a - b导致0,则返回0.(a和b在订购时相同)

因此...

 if (key.compareTo(midValue) < 0) {

      //look to the left of mid
 }...