我需要在具有各种数据类型的链表上执行二进制搜索。下面的代码将无法编译。我似乎无法使compareTo()工作。
这是链表类:
public class Contributor {
private String firstName;
private String lastName;
private String country;
private String phone;
private double contribution;
private int id;}
二进制搜索方法如下。搜索需要使用二进制搜索方法找到某个lastName。
public void binarySearch(List<Contributor> l, String key) {
System.out.println("Binary search.");
int upperBound = l.size();
int lowerBound = 1;
int midpoint = (upperBound + lowerBound) / 2;
int difference = upperBound - lowerBound;
for (int i = 0; i < l.size(); i++) {
if (key.compareTo(l.get(midpoint - 1))&& difference != 1) {
upperBound = midpoint - 1;
midpoint = upperBound / 2;
} else if (key.compareTo(l.get(midpoint - 1)) && difference != 1) {
lowerBound = midpoint + 1;
midpoint = (lowerBound + upperBound) / 2;
} else if (key.equals(l.get(midpoint - 1))) {
midpoint = midpoint - 1;
System.out.println("We found " + key + " at position " + midpoint + " in the list.");
i = l.size();
} else {
System.out.println("We couldn't find " + key + " in the list.");
i = l.size();
}
}
}
答案 0 :(得分:0)
通过查看代码,l.get(midpoint-1)返回的是Contributor对象而不是String,而key.compareTo方法只能接受String类型的参数。
答案 1 :(得分:0)
compareTo()函数返回整数值。所以试试
if(key.compareTo(str) < 0)
或
if(key.compareTo(str) > 0)
或
if(key.compareTo(str) == 0)
还要将它与Contributor类中的String进行比较,而不是与类本身进行比较。
if(key.compareTo((l.get(midpoint - 1)).firstName)<0)
另一个逻辑错误是当你做
时midpoint = upperBound / 2;
您假设lowerbound
1 。但它的价值可能会在迭代中发生变化。所以考虑一下
答案 2 :(得分:0)
这里有一个逻辑错误 - 正如Akshay所说,你的密钥是String
,因此在Contibutor
列表中搜索它是没有意义的 - 你需要搜索对于Contributor
。
除此之外,二进制搜索的前提条件是列表已排序,这要求您的Contributor
对象为Comparable
(或者至少提供Comparator
。
我已修改您的代码以解决这些问题:
class Contributor implements Comparable<Contributor>{
private String firstName;
private String lastName;
private String country;
private String phone;
private double contribution;
private int id;
public int compareTo(Contributor o) {
return Integer.valueOf(id).compareTo(o.id);
}
}
public class BinarySearch {
/**
* Performs a binary search for <code>key</code> in the list <code>l</code>.
*
* @param l Ordered list of Contributors.
* @param key Value to search for.
*/
public void binarySearch(List<Contributor> l, Contributor key) {
System.out.println("Binary search.");
int upperBound = l.size();
int lowerBound = 1;
int midpoint = (upperBound + lowerBound) / 2;
int difference = upperBound - lowerBound;
for (int i = 0; i < l.size(); i++) {
if (key.compareTo(l.get(midpoint - 1)) <0 ) {
upperBound = midpoint - 1;
midpoint = upperBound / 2;
} else if (key.compareTo(l.get(midpoint - 1))>0 ) {
lowerBound = midpoint + 1;
midpoint = (lowerBound + upperBound) / 2;
} else if (key.equals(l.get(midpoint - 1))) {
midpoint = midpoint - 1;
System.out.println("We found " + key + " at position "
+ midpoint + " in the list.");
i = l.size();
} else {
System.out.println("We couldn't find " + key + " in the list.");
i = l.size();
}
}
}
}
这应该可以修复你的编译错误,尽管其他人注意到,搜索逻辑本身也有一些错误。另请注意,binarySearch
方法的前提条件是订购列表,并且应记录此要求。我添加了一个javadoc注释来解释这个。