二进制搜索compareTo String对象

时间:2016-10-13 00:45:58

标签: java arrays sorting binary-search compareto

class ObjectBinarySearcher{

    public static int search(String[] array, String value){

        int first = 0, last = array.length-1, position = -1;
        boolean found = false;

        while(!found && first < last){
            int mid = (first+last)/2;
            int midValue = array[mid].compareTo(value);

            if(midValue==0){
                position = mid;
                found = true;
            }
            else if(midValue<0)
                last = mid-1;
            else
                first = mid+1;
        }

        return position;
    }
}

我发送的数组包含{“love”,“hate”,“happy”,“sad”,“neutral”},每当我尝试使用二进制搜索方法搜索“中性”时,它告诉我它没有找到。是什么导致这种情况发生?

2 个答案:

答案 0 :(得分:1)

  1. 必须对输入数组进行排序才能使用二进制搜索。

  2. 正如@Libby指出的那样,你的while循环需要改变为允许第一个小于或等于last。

  3. 如果first == last找不到匹配项,您需要退出循环。

  4. 如果midValue&lt; 0你需要移动下限,而不是上限(反之亦然)。

  5. 新代码

    while (!found && first <= last) { // allow first to be lower or equal to last
        int mid = (first + last) / 2;
        int midValue = array[mid].compareTo(value);
    
        if (midValue == 0) { // matched!
    
            position = mid;
            found = true;
    
        } else if (first == last) { // didn't match and there was only one left to check
    
            break; // so break out of the loop
    
        } else if (midValue < 0) { // current pos is too low
    
            first = mid + 1; // so adjust the lower bound
    
        } else { // current pos is too high
    
            last = mid - 1; // so adjust the upper bound
    
        }
    }
    

答案 1 :(得分:0)

while loop更改为while(!found && first <= last)