Java program to implement binary search algorithm
Here's a Java program that implements the binary search algorithm:
import java.util.Arrays; public class BinarySearch { public static void main(String[] args) { int[] array = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }; int searchValue = 12; int index = binarySearch(array, searchValue); if (index != -1) { System.out.println(searchValue + " found at index " + index); } else { System.out.println(searchValue + " not found in array"); } } public static int binarySearch(int[] array, int searchValue) { int left = 0; int right = array.length - 1; while (left <= right) { int mid = (left + right) / 2; if (array[mid] == searchValue) { return mid; } else if (array[mid] < searchValue) { left = mid + 1; } else { right = mid - 1; } } return -1; } }Sourec:www.theitroad.com
In this program, we define an array of integers, and a variable to hold the value we're searching for. We then call the binarySearch
method, passing in the array and the search value as arguments. If the value is found, the method returns the index of the value in the array. If the value is not found, the method returns -1.
The binarySearch
method takes an array and a search value as inputs, and returns the index of the search value in the array, or -1 if the value is not found. The method uses two variables, left
and right
, to define the range of the search. It then enters a loop that continues while left
is less than or equal to right
. In each iteration of the loop, the method calculates the midpoint of the range by adding left
and right
, and dividing by 2. If the midpoint value is equal to the search value, the method returns the midpoint index. If the midpoint value is less than the search value, the method updates left
to be one position to the right of the midpoint. If the midpoint value is greater than the search value, the method updates right
to be one position to the left of the midpoint. The method repeats this process until it either finds the search value or determines that the value is not present in the array.