How do you call the Java binary search algorithm?
The steps to invoke a binary search algorithm in Java are as follows:
- Create an array and make sure it is already sorted.
- Call the binary search algorithm method, passing in the target value to be searched for and the array to be searched.
- Implement the binary search algorithm in the method by passing in the target value and the array, and finally return the position of the target value in the array.
Here is an example code:
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;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13};
int target = 7;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("目标值不存在数组中");
} else {
System.out.println("目标值在数组中的位置是:" + result);
}
}
}
In the above example, we first define a binarySearch method to implement the binary search algorithm, then in the main method we create a sorted array called arr and a target value called target, and finally call the binarySearch method to find the position of the target value in the array.