在对象中实现二分查找
有什么方法可以在带有对象的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 )”会是什么样子? 这可能吗?
Is there any way to implement binary search in a ArrayList with objects? In this example the ArrayList will be sorted with the field '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);
How would the "User getUserById( ArrayList users, int userid )" look like if I it should return the user with a specified id using binary search? Is this even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
The Java Tutorials 的 对象排序 文章中有一个示例编写自己的
Comparator
< /a> 以便对自定义类型进行比较。然后,
ArrayList
(或任何其他List
)、要查找的键以及Comparator
可以传递到Collections.binarySearch
方法。这是一个例子:
The Object Ordering article of The Java Tutorials has an example of writing your own
Comparator
in order to perform comparisons on custom types.Then, the
ArrayList
(or any otherList
), the key to find, along withComparator
can be passed into theCollections.binarySearch
method.Here's an example:
您还可以将比较器放在 User 类中:
然后您将对名为 users 的 ArrayList 执行以下操作:
You could also put the comparator in the User class:
Then you would do the following to an ArrayList called users:
将
Collections.binarySearch
与Comparator
结合使用。Use
Collections.binarySearch
with aComparator
.您应该仅在排序的 ArrayList 上使用 binarySearch 方法。 所以首先对 ArraList 进行排序,并使用相同的比较器引用(用于进行排序)来执行 binarySearch 操作。
You should use binarySearch method only on the sorted ArrayList. so First sort the ArraList and use the same comparator reference (which you used to do the sort) to perform the binarySearch operation.