检查语法错误public class Test01 { public static void main(String[] args) { int[] arr = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; int element = 18; System.out.println(element + "在数组中的索引位置为:" + mid); System.out.println(element + "在数组中的索引位置为:" + -1); } public static int binarySearch(int[] arr,int element) { int min = 0; int max = arr.length - 1; while (true) { int mid = (min + max) / 2; if (element > arr[mid]) { min = mid + 1; } else if (element < arr[mid]) { max = mid - 1; } else { return mid; } if (min > max) { return -1; } } } }
时间: 2023-12-10 19:38:06 浏览: 143
C#中static void Main(string[] args) 参数示例详解
在main方法中,需要调用binarySearch方法获取索引位置,而mid变量未定义。修改为以下代码即可:
```
public class Test01 {
public static void main(String[] args) {
int[] arr = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int element = 18;
int index = binarySearch(arr, element);
System.out.println(element + "在数组中的索引位置为:" + index);
if (index == -1) {
System.out.println("元素不在数组中");
}
}
public static int binarySearch(int[] arr, int element) {
int min = 0;
int max = arr.length - 1;
while (true) {
int mid = (min + max) / 2;
if (element > arr[mid]) {
min = mid + 1;
} else if (element < arr[mid]) {
max = mid - 1;
} else {
return mid;
}
if (min > max) {
return -1;
}
}
}
}
```
阅读全文