【发布时间】:2015-05-08 21:27:46
【问题描述】:
我正在尝试在字符串数组上创建具有多个匹配项的二进制搜索。我尝试了多种不同的方法,但我似乎无法让它发挥作用。
我当前的代码是这样的:
public static void searchSinger(Music2[] r, String toFind) {
int high = r.length;
int low = -1;
int probe;
while (high - low > 1) {
probe = (high + low) / 2;
if (r[probe].getSinger().compareTo(toFind) > 0) high = probe;
else {
low = probe;
if (r[probe].getSinger().compareTo(toFind) == 0) {
break;
}
}
}
if ((low >= 0) && (r[low].getSinger().compareTo(toFind) == 0)) {
linearPrint(r, low, toFind);
} else System.out.println("Not found: " + toFind);
}
public static void linearPrint(Music2[] r, int low,
String toFind) {
int i;
int start = -1;
int end = -1;
// find starting point of matches
i = low - 1;
while ((i >= 0) && (r[i].getSinger().compareTo(toFind) == 0)) {
start = i;
i--;
}
// find ending point of matches
i = low + 1;
while ((i < r.length) && (r[i].getSinger().compareTo(toFind) == 0)) {
end = i;
i++;
}
// now print out the matches
for (i = start; i <= end; i++)
System.out.println(r[i]);
}
如果我调用诸如
之类的代码searchSinger(myLibrary, "Eminem");
而 Eminem 确实存在于 myLibrary 中,它会返回
"Not found: Eminem"
所以我的问题是,我在这里做错了什么?我真的很想让它工作,但我自己似乎无法调试它。
编辑: 这是我正在使用的排序算法:
public static void selectionSort(Music2[] list) {
int i;
int k;
int posmax;
Music2 temp;
for (i = list.length - 1; i >= 0; i--) {
// find largest element in the i elements
posmax = 0;
for (k = 0; k <= i; k++) {
if (list[k].getYear() > list[posmax].getYear()) posmax = k;
}
// swap the largest with the position i
// now the item is in its proper location
temp = list[i];
list[i] = list[posmax];
list[posmax] = temp;
}
}
【问题讨论】:
-
这有什么意义?要进行二分搜索,您需要一个已排序的输入。一旦你找到你的搜索词的第一次出现,检查下一个/上一个条目以查看是否还有更多是一件简单的事情 - 但这不再是二进制搜索,这是简单的线性数组/列表遍历
-
算法在我看来是正确的。我认为输入没有正确排序,或者它不包含您正在寻找的字符串(或者,它可能是在不同的情况下,或者有一个您没有注意到的空格或点或类似的东西那个)。
-
我正在使用选择排序来对数组进行排序,我会将其添加到帖子中。