To implement a binary search algorithm in Java, we first need to have a sorted array. The algorithm works by repeatedly dividing the search interval in half until the target element is found or the interval is empty.Here's the basic implementation in Java:
```javapublic static int binarySearch(int[] arr, int target) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == target) {
return mid;
}
else if (arr[mid] < target) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return -1;
// Target not found}
```In this implementation, we initially set the start and end indices to the beginning and end of the array, respectively. We then repeatedly calculate the midpoint of the current search interval and compare it to the target element. If the midpoint is equal to the target, we return its index. If the midpoint is less than the target, we update the start index to be one after the midpoint. Otherwise, we update the end index to be one before the midpoint. This process continues until we either find the target or the search interval is empty.It's worth noting that the binary search algorithm only works on sorted arrays. If the array is not sorted, we would need to sort it first before using the algorithm.References:
- Oracle. (n.d.). BinarySearch. Retrieved from https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#binarySearch-int:A-int-- GeeksforGeeks. (n.d.). Binary Search. Retrieved from https://www.geeksforgeeks.org/binary-search/