当前位置: 首页 > 面试题库 >

在对象中实现二进制搜索

仲浩歌
2023-03-14
问题内容

有什么方法可以在具有对象的ArrayList中实现二进制搜索?在此示例中,ArrayList将使用字段“ id”进行排序。

class User{
 public int id;
 public string name;
}

ArrayList<User> users = new ArrayList<User>();

sortById(users);

int id = 66
User searchuser = getUserById(users,id);

如果我应该使用二进制搜索返回具有指定ID的用户,“ User getUserById(ArrayList users,int
userid)”将如何?这有可能吗?


问题答案:

Java教程的对象排序文章中有一个示例,您可以编写自己的示例Comparator以对自定义类型进行比较。

然后,ArrayList(或任何其他List),要查找的键以及Comparator可以一起传递到Collections.binarySearch方法中。

这是一个例子:

import java.util.*;

class BinarySearchWithComparator
{
  public static void main(String[] args)
  {
    // Please scroll down to see 'User' class implementation.
    List<User> l = new ArrayList<User>();
    l.add(new User(10, "A"));
    l.add(new User(20, "B"));
    l.add(new User(30, "C"));

    Comparator<User> c = new Comparator<User>() {
      public int compare(User u1, User u2) {
        return u1.getId().compareTo(u2.getId());
      }
    };

    // Must pass in an object of type 'User' as the key.
    // The key is an 'User' with the 'id' which is been searched for.
    // The 'name' field is not used in the comparison for the binary search,
    // so it can be a dummy value -- here it is omitted with a null.
    //
    // Also note that the List must be sorted before running binarySearch,
    // in this case, the list is already sorted.

    int index = Collections.binarySearch(l, new User(20, null), c);
    System.out.println(index);    // Output: 1

    index = Collections.binarySearch(l, new User(10, null), c);
    System.out.println(index);    // Output: 0

    index = Collections.binarySearch(l, new User(42, null), c);
    System.out.println(index);    // Output: -4
                                  // See javadoc for meaning of return value.
  }
}

class User {
  private int id;
  private String name;

  public User(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public Integer getId() {
    return Integer.valueOf(id);
  }
}


 类似资料:
  • 问题内容: 我正在编写一个使用二进制搜索树存储数据的程序。在以前的程序中(无关),我能够使用Java SE6随附的实现来实现链表。二进制搜索树是否有类似的东西,还是我需要“从头开始”? 问题答案: 您可以使用。被实现为一棵红黑树,这是一个自平衡二进制搜索树。

  • 问题内容: 这是我到目前为止所获得的,但是没有用: 问题答案: 这是二进制插入的快速示例:

  • 我正在尝试实现一个二叉查找树,但是“搜索”函数对于除了根之外的每个条目都返回了错误的值。 该函数应返回其值与键参数匹配的节点的地址,如果节点不存在,则返回 NULL。 当我运行代码时,我得到以下内容: 我知道每个节点的“左”和“右”指针链接正确,因为“delAll”函数成功删除了所有节点。 将“cout”语句添加到“search”函数表明该函数似乎返回了正确的地址。为什么从主主调用时会打印错误的地

  • 我使用这个二进制搜索函数得到一个较大数据集的索引错误。当我输入一个较小的数据集时,即[1,2,3,4,5]搜索5。算法按预期运行。但是,当我获取下面的文本时,使用空参数列表(delimeter char为“”)调用string对象的split方法,并将字符串拆分为列表值,其中每个元素都是字符串,然后搜索单词“culpa”,我最终会出现以下错误: 索引错误:列表索引超出范围 非常感谢你的帮助。非常感

  • 我正在尝试使用递归在python中实现二进制搜索树。我被困在程序中发生的一些无限递归中。我通过传递地址和数据对函数RecursBST进行递归调用,直到顶部遍历到它的左或右子级的None值为止。 我运行到以下错误:

  • 问题内容: 我在将这两种算法结合在一起时遇到麻烦。我被要求修改以返回将元素插入数组的索引。然后有人要求我实现一个使用my 对随机生成的数组进行排序的。 我按照预期的方式工作,每当我单独测试它时都返回正确的索引。我写信是为了了解它是如何工作的,并使其也能工作。一旦将两者结合在一起,它就会崩溃。我知道我在一起实施起来不正确,但是我不确定问题出在哪里。 这是我得到的: 我在运行它时得到的返回值是。有什么