【发布时间】:2017-06-20 19:17:19
【问题描述】:
我得到了一些包含 Person 对象数组的代码,我要编写方法来执行二进制搜索并覆盖 Person 类中的 compareto 方法,以根据姓氏和名字进行比较。
public static int binarySearch( Person[] persons, Person key )
{
int low = 0;
int high = persons.length - 1;
return binarySearch(persons, key, low, high);
}
private static int binarySearch( Person[]persons, Person key, int low, int high )
{
if(low > high) //The list has been exhausted without a match.
return -low - 1;
int mid = (low + high) / 2;
if (persons[mid] == key)
return mid;
if(persons[mid] < key) //!!**'The < operator is undefined for the type'
return binarySearch(persons, key, low, mid-1);
else
return binarySearch(persons, key, 0, persons.length -1);
}
我想我已经编写了大部分二进制搜索代码。但是,我遇到的问题是在 if(persons[mid]
我认为它可能与我的 compareTo 方法有关,但我似乎无法修复它
这里是 compareTo 供参考
public int compareTo( Object o )
{
Person p = (Person) o;
int d = getLastName().compareTo(p.getLastName());
if (d == 0)
d = getFirstName().compareTo(p.getFirstName());
return d;
}
感谢您的帮助!
【问题讨论】:
-
if(persons[mid] < key) I get the error 'The < operator is undefined for the type'.确定不是<和>没有为objects定义
标签: java binary-search compareto