温馨提示×

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

小樊
84
2024-06-25 17:31:30
栏目: 编程语言

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

0