0

我得到了一些包含 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] < key) 我收到错误“< operator is undefined for the type”。

我认为它可能与我的 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;
   }

感谢您的任何帮助!

4

3 回答 3

1

Try this:

int mid = (low + high) / 2;
if (persons[mid].compareTo(key) == 0)
    return mid;
if(persons[mid].compareTo(key) < 0)
    return binarySearch(persons, key, low, mid-1);
else 
    return binarySearch(persons, key, 0, persons.length -1);

You can not compare Objects using < > like operators.

于 2013-10-16T18:54:49.227 回答
1

代替

if(persons[mid] < key) 

利用

if(persons[mid].compareTo(key) < 0) 
于 2013-10-16T18:51:48.007 回答
0

您正在比较两个对象引用,它们只包含指向实际人员对象位置的位模式。对于对象比较,您需要定义要比较它们的属性(属性)。所以试试这个

    if (persons[mid].compareTo(key) == 0)
        return mid;
    if(persons[mid].compareTo(key) < 0)

还要检查 binarySearch 的正确实现。

     return binarySearch(persons, key, mid +1, high);
else
     return binarySearch(persons, key, low, mid -1);

而且您还没有 在 compareTo 中使用它。应该是这样的

public int compareTo( Object o )
   {
      Person p = (Person) o;
      int d = this.getLastName().compareTo(p.getLastName());
      if (d == 0)
          d = this.getFirstName().compareTo(p.getFirstName());
      return d;
   }

您的人员数组也排序了吗?

于 2017-06-20T11:02:29.283 回答