java - 二进制搜索字符串数组

标签 java arrays binary-search

如何对字符串数组进行二分查找排序。在下面,我的索引总是收到一个负数,而不是正确的索引。请帮忙?如果单词不在数组中,则应返回 -1。

  public static int binary (String [] theword, String a) {
    int index = -1;
        Arrays.sort(theword);
        Arrays.toString(theword);
        index = Arrays.binarySearch(theword, a);
    return index;

}   

最佳答案

有效,见下文

public static void main(String... args) {

    String words[] = { "abc3", "abc2", "abc1", "abc4" };

    Arrays.sort(words);
    System.out.println(Arrays.toString(words));
    {
        String word = "abc3";
        int index = Arrays.binarySearch(words, word);
        index = index >= 0 ? index : -1;
        System.out.println(word + " = " + index);
    }
    {
        String word = "abc11";
        int index = Arrays.binarySearch(words, word);
        index = index >= 0 ? index : -1;
        System.out.println(word + " = " + index);
    }
}

输出

[abc1, abc2, abc3, abc4]
abc3 = 2
abc11 = -1

当您需要原始数组的索引时,您返回排序后数组的索引。

关于java - 二进制搜索字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16087987/

相关文章:

java - 使用 JpaRepository 注入(inject) Autowiring 依赖项失败

algorithm - Clog n的一个算法问题的设计[C++代码]

javascript - React 映射数组并仅返回标签

ios - 致力于开发库存应用程序。我正在尝试在 Realm 中保存多个对象

c - 在多个结构指针和数组中为结构指针的成员赋值

c - C 中的二进制搜索

c++ - 二进制搜索没有返回正确的值

java - 设置属性 : Non-serializable attribute (Java Object Serialization)

java - 如何让 docker 容器向同一网络中运行的另一个容器发送 HTTP 请求

java - 所选目录不是 JDK 的有效主目录 - Windows 上的 Intellij IDEA2016