您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 Java 中,二分搜索(Binary Search)通常用于在一个已排序的数组中查找指定元素
public class BinarySearch {
public static void main(String[] args) {
int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15};
int target = 7;
int index = binarySearch(sortedArray, target);
if (index != -1) {
System.out.println("元素 " + target + " 在数组中的索引为: " + index);
} else {
System.out.println("元素 " + target + " 不在数组中");
}
}
public static int binarySearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
return mid;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // 如果找不到目标元素,返回 -1
}
}
这个示例中,我们首先定义了一个已排序的整数数组 sortedArray
和一个目标值 target
。然后,我们调用 binarySearch
方法来查找目标值在数组中的索引。如果找到目标值,binarySearch
方法返回其在数组中的索引;否则,返回 -1。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。