当使用二分查找时,如果目标元素不在数组中,则该算法将返回一个负数。这是因为它使用了补码来表示结果。为了避免这种情况,可以在返回值上执行一次检查,或在实现中使用一个不同的返回方式。
以下是一个使用二分查找的示例,其中包含返回值检查:
public static int binarySearch(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// 如果没有找到目标元素,则返回 -1
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11};
int target = 4;
int result = binarySearch(arr, target);
if (result < 0) {
System.out.println("目标元素不在数组中");
} else {
System.out.println("目标元素的索引为:" + result);
}
}