所以我要重写两个函数,从使用顺序搜索到二进制搜索。我理解两者在效率上的差异,然而,在将它们改为二进制时,我在语法上遇到了问题。
类
public class SortedList<Item extends Comparable<Item>> implements SortedList<Item> {
private Object[] data = new Object[5];
private int size = 0;
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean equals(Object o) {
SortedList<Item> lst = (SortedList<Item>) o;
if (size != lst.size)
return false;
Iterator<Item> i1 = lst.iterator();
Iterator<Item> i2 = iterator();
while (i1.hasNext()) {
Item x1 = i1.next();
Item x2 = i2.next();
if (!x1.equals(x2))
return false;
}
return true;
}
//METHOD TO CHANGE TO BINARY-SEARCH
public int indexOf(Item x) {
int low = 0, high = size - 1;
while (low <= high) {
int mid = (low + high) / 2;
if ((int) x == mid)
return mid;
else if ((int) x > mid)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}主
public class Main {
public static void main(String[] args) {
SortedList<Integer> s = new SortedList<Integer>();
s.add(5);
s.add(6);
s.add(7);
s.add(8);
s.add(9);
s.add(10);
System.out.println(s.indexOf(6)); //-1
}
}基本上,我很难将Item x和整数进行比较。看起来,即使当我将x转换为和Int时,函数仍然返回-1。在这个函数中,我比较正确的方法是什么?我也可以提供更多的代码,如果有必要,我包括所有我认为是相关的。
发布于 2016-05-23 21:49:39
您混淆了列表中的索引和元素:
if ((int) x == mid)你想:
if(x.equals(itemAtIndex(mid)))https://stackoverflow.com/questions/37401061
复制相似问题