酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

超详细!Java二分法算法实现代码及原理剖析

以下是一个简单的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 = {2, 3, 4, 10, 40}; int target = 10; int result = binarySearch(arr, target); if (result != -1) { System.out.println("元素在数组中的索引为: " + result); } else { System.out.println("元素不在数组中"); } } } ``` 这个代码首先定义了一个左边界`left`和一个右边界`right`,然后在while循环中,计算中间元素的索引`mid`。如果中间元素等于目标元素,就返回`mid`。如果中间元素小于目标元素,就将左边界移动到`mid+1`。如果中间元素大于目标元素,就将右边界移动到`mid-1`。如果循环结束都没有找到目标元素,就返回-1表示目标元素不在数组中。 ######[AI写代码神器 | 342点数解答 | 2023-12-27 11:41:47]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]