二进制搜索(字符串值):尝试搜索用户名

所以我有一个二进制搜索功能。我需要搜索目标是数组中给定的用户名。

为了进行迭代,我正在使用compareTo函数将给定的用户名字符串与列表中的一个进行比较(是否有更好的方法呢?)。

问题:当列表中有两个成员用户名时,找到用户名。但是,使用3个用户名时,二进制搜索会崩溃(找不到任何内容)。

注意:我注意到起始中点似乎总是数组中的最后一个索引(?)

这是功能

private  Member binarySearch(Member[] sortedArray, String target) {
  int l = 0;
  int r = sortedArray.length - 1;
  int midpoint = -1;

while (l <= r) {
    midpoint = l + (r - l)/2;

    if(sortedArray.length == 0) {
        return null; // list and divided to the point all elements check, and not found.
    }

        if (sortedArray[midpoint] !=null &&
                target.compareTo(sortedArray[midpoint].getUsername()) == 0) { // eventually the only element left after recursive elimination will be midpoint  i.e.
            System.out.println("midpoint found: " + sortedArray[midpoint].getUsername());

            return sortedArray[midpoint]; // member username found for the given "target" member id
        } else if (sortedArray[midpoint] !=null &&
                target.compareTo(sortedArray[midpoint].getUsername()) > 0) { // midpoint greater than target
            l = midpoint + 1;
            if(sortedArray[midpoint] !=null) {
                System.out.println("right side:User searching..." + sortedArray[midpoint].getUsername()
                + " at index" + midpoint);
            }
        } else { // midpoint is less than target
            r = midpoint - 1;
            if(sortedArray[midpoint] !=null) {
                System.out.println("left side:User searching..." + sortedArray[midpoint].getUsername());
            }
        }

}

return null; // array given is length 0 or 1 element.
}

我调用binarySearch的函数:

public Member find(String username) {
                Member foundMember = this.binarySearch(this.member, username);

                if(foundMember != null) {
                    return foundMember;
                } else {
                    return null;
                }
            }

一些添加到成员数组的函数

function xx() {
        this.members[0] = admin;
        this.members[1] = testUser;
        this.members[2] = bri;  // if i remove this element it finds the prev two ?!
}