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