用java语言写一个二分查找
时间: 2023-11-25 13:55:44 浏览: 41
算法,你能给我讲讲吗?
当然可以!二分查找算法的基本思想是将有序数组不断折半,对比中间位置元素与目标元素的大小关系,不断缩小查找范围,直到找到目标元素为止。具体实现可以参考下面的代码:
```
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target == arr[mid]) {
return mid;
} else if (target < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1; //如果没找到,返回-1
}
```
以上就是二分查找算法的基本实现。希望能对你有所帮助!
相关问题
写一个二分查找用java语言
以下是使用Java语言编写的二分查找算法:
```java
public class BinarySearch {
public static int search(int[] arr, int x) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13};
int x = 7;
int result = search(arr, x);
if (result == -1) {
System.out.println("元素不存在");
} else {
System.out.println("元素位置为:" + result);
}
}
}
```
在该代码中,`search`方法使用循环实现了二分查找算法。首先,将数组中第一个元素的索引赋给`low`变量,将数组中最后一个元素的索引赋给`high`变量。然后,在while循环中,计算数组的中间索引,并将中间元素与目标元素进行比较。若中间元素等于目标元素,则返回中间索引;若中间元素小于目标元素,则将数组的左半部分作为新的查找区间;否则,将数组的右半部分作为新的查找区间。最终,若目标元素不存在于数组中,则返回-1。
用JAVA语言写一段二分查找的代码
// 二分查找的代码:
public class BinarySearch {
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;
}
}
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)