在Java中,可以使用Collections类的binarySearch()方法来实现对List进行二分查找。
示例代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BinarySearchExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(2);
numbers.add(5);
numbers.add(7);
numbers.add(10);
numbers.add(15);
// 对List进行排序
Collections.sort(numbers);
int key = 7;
// 使用binarySearch方法进行二分查找
int index = Collections.binarySearch(numbers, key);
if (index >= 0) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}
在上述代码中,首先创建一个包含整数的List,并对其进行排序。然后使用Collections类的binarySearch()方法来查找指定元素的索引位置。如果找到了元素,则返回它的索引值,否则返回一个负数。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1081400.html