温馨提示×

Java定义list如何实现二分查找

小樊
115
2024-06-25 17:31:30
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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()方法来查找指定元素的索引位置。如果找到了元素,则返回它的索引值,否则返回一个负数。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:kotlin list如何实现二分查找

0