简体   繁体   English

递归二进制搜索Java

[英]Recursive Binary Search Java

I have an arraylist called sArray that holds a large list of correctly spelled words. 我有一个名为sArray的arraylist,其中包含一大堆正确拼写的单词。 I need to send a word to this recursive binary search method (key) and determine whether or not it is spelled correctly or not. 我需要向这个递归二进制搜索方法(密钥)发送一个单词,并确定它是否拼写正确。 I understand how a recursive binary search works however I am not sure how to determine whether or not I need to go left or right in searching sArray with my key word since I am dealing with Strings and not integers. 我理解递归二进制搜索是如何工作的但是我不知道如何确定我是否需要向左或向右搜索带有关键字的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);
    }
}

You can just as easily compare Strings as integers: 您可以轻松地将字符串与整数进行比较:

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

The compareTo method lets you compare any object that implements the Comparable interface. compareTo方法使您可以比较实现Comparable接口的任何对象。 Since the String class implements the Comparable interface, compareTo will work in your method. 由于String类实现了Comparable接口,因此compareTo将在您的方法中起作用。

A handy trick to remember when using compareTo is thinking of it like subtraction: 使用compareTo时要记住一个方便的技巧,就像减法一样:

a.compareTo(b) will return -1 if a - b results in a negative answer. 如果a - b导致否定答案,则a.compareTo(b)将返回-1。 (a comes before b when ordering them) (a在订购时出现在b之前)

a.compareTo(b) will return 1 if a - b results in a positive answer. 如果a - b得到肯定答案,a.compare(b)将返回1。 (a comes after b when ordering them) (在订购时,b来自b)

a.compareTo(b) will return 0 if a - b results in 0. (a and b are identical when ordered) 如果a-b的结果为0,则a.compareTo(b)将返回0。(订购时a和b相同)

So... 所以...

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM