您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
二分搜索(Binary Search)是一种高效的查找算法,其基本思想是每次将待查找的区间缩小一半,直到找到目标元素或确定目标元素不存在。二分搜索的时间复杂度为 O(log n),其中 n 是数组的长度。
在 Java 中,可以使用 Arrays.binarySearch()
方法来实现二分搜索。这个方法的时间复杂度也是 O(log n)。以下是一个简单的示例:
import java.util.Arrays;
public class BinarySearchExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 5;
int index = Arrays.binarySearch(arr, target);
if (index >= 0) {
System.out.println("目标元素 " + target + " 在数组中的索引为:" + index);
} else {
System.out.println("目标元素 " + target + " 不存在于数组中");
}
}
}
在这个示例中,我们使用 Arrays.binarySearch()
方法在有序数组 arr
中查找目标元素 target
。如果找到目标元素,方法将返回其在数组中的索引;否则,返回一个负数。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。