📜  Java中的 Arrays.binarySearch() 示例 | Set 2(在子数组中搜索)(1)

📅  最后修改于: 2023-12-03 15:01:50.573000             🧑  作者: Mango

Java中的 Arrays.binarySearch() 示例 | Set 2(在子数组中搜索)

Arrays.binarySearch() 方法是 Java 中常用的二分搜索算法。它可以用于在整个数组中搜索给定元素的索引。本篇文章将介绍如何在子数组中搜索元素。

Arrays.binarySearch() 方法详解
public static int binarySearch(int[] a, int fromIndex, int toIndex, int key)

fromIndextoIndex-1 范围内搜索 key 元素的索引。如果在该范围内找到 key,则返回其索引;否则,返回 -(插入点)-1

注意:在使用 binarySearch() 方法前需要先排序数组。

示例代码
import java.util.Arrays;

public class BinarySearchInSubArrayExample {
    public static void main(String args[]) {
        int a[] = { 10, 20, 15, 22, 35 };
        Arrays.sort(a);
        int key = 22;
        int index = Arrays.binarySearch(a, 1, 4, key);
        if (index < 0)
            System.out.println(key + " 不在 a 数组中,应该插入位置为 " + -(index + 1));
        else
            System.out.println(key + " 在 a 数组中的索引为 " + index);
    }
}

以上代码中,a[] 数组分别为 {10, 20, 15, 22, 35}。在使用 binarySearch() 方法前先对 a[] 数组进行排序。然后,我们要搜索的元素是 22,忽略第一个和最后一个元素。最后,程序会输出 22a[] 数组中的索引。

输出结果:

22 在 a 数组中的索引为 2
总结

本篇文章介绍了如何使用 Arrays.binarySearch() 方法来在子数组中搜索指定元素,并给出了完整的示例代码。在使用 binarySearch() 方法时需要注意:

  • 使用前需要先对数组排序。
  • 如果该元素在数组中,返回其索引;否则,返回 -(插入点)-1