用JAVA实现一个二分查找
时间: 2023-08-31 12:41:42 浏览: 70
### 回答1:
二分查找是一种在有序数组中查找特定元素的快速算法。下面是用 Java 实现二分查找的代码示例:
```
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (array[mid] == target) {
return mid;
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
```
在上面的代码中,首先定义了左右两个指针 `left` 和 `right`,分别表示数组的左边界和右边界。在每次查找的过程中,我们计算中间索引 `mid`,并比较该索引对应的元素与目标元素的值,根据比较结果缩小查找范围,直到找到目标元素为止。如果最终查找失败,则返回 -1。
### 回答2:
二分查找是一种在有序数组中查找元素的算法。实现二分查找可以通过递归或迭代的方式来实现,下面是用JAVA编写的迭代实现代码:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // 如果找不到目标元素,返回-1
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 6;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("目标元素不存在");
} else {
System.out.println("目标元素在数组中的索引为:" + result);
}
}
}
```
以上代码实现了一个迭代版本的二分查找,首先定义了左边界和右边界,然后通过循环不断缩小查找范围,直到找到目标元素或者查找范围为空。如果找到了目标元素,则返回其在数组中的索引,否则返回-1表示目标元素不存在。
在以上代码中,需要查找的目标元素是6,该元素在数组中的索引为5,因此输出结果为"目标元素在数组中的索引为:5"。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)