admin 管理员组

文章数量: 1184232


2024年3月29日发(作者:免费网站大全下载你知道的)

array数组binarysearch方法

在 Java 中,数组类(`Arrays` 类)提供了一个 `binarySearch` 方法,用于对排序后的数组

进行二分查找。这个方法有多个重载形式,其中包括对整型数组、对象数组和某个范围内的

数组进行二分查找。以下是一些常见用法:

1. 对整型数组进行二分查找:

```java

import ;

public class BinarySearchExample {

public static void main(String[] args) {

int[] array = {1, 2, 4, 7, 10, 15};

int key = 7;

// 对排序后的数组进行二分查找

int index = Search(array, key);

if (index >= 0) {

n("Element " + key + " found at index " + index);

} else {

n("Element " + key + " not found in the array");

}

}

}

```

2. 对对象数组进行二分查找:

如果数组是对象数组,确保对象实现了 `Comparable` 接口或提供了自定义的比较器。

```java

import ;

public class BinarySearchObjectArrayExample {

public static void main(String[] args) {

String[] array = {"apple", "banana", "orange", "pear"};

String key = "orange";

// 对排序后的对象数组进行二分查找

int index = Search(array, key);

if (index >= 0) {

n("Element " + key + " found at index " + index);

} else {

n("Element " + key + " not found in the array");

}

}

}

```

3. 对数组的指定范围进行二分查找:

```java

import ;

public class BinarySearchRangeExample {

public static void main(String[] args) {

int[] array = {1, 2, 4, 7, 10, 15};

int key = 7;

// 对指定范围的数组进行二分查找

int index = Search(array, 0, 4, key);

if (index >= 0) {

n("Element " + key + " found at index " + index);

} else {

n("Element " + key + " not found in the specified range");

}

}

}

```

在使用 `binarySearch` 方法之前,确保数组已经按升序排序。如果数组中包含多个相同的元

素,`binarySearch` 方法无法保证找到的是哪一个。


本文标签: 数组 进行 方法 查找 对象