Binary Search Program
import
java.util.Arrays;
public class BinarySearchProgram
{
public static void main(String[] args) {
int arr[] = {10, 20, 30,
40, 50};
int key = 30;
// The value we want to search for in the array.
int result = Arrays.binarySearch(arr, key);
// Performing binary search on the array for the
key.
if (result < 0)
System.out.println("Element
is not found!");
// The binarySearch method returns a negative
value if the key is not found.
else
System.out.println("Element is found at index: " + result);
// If the key is found, the binarySearch method
returns its index in the array.
}
}
Output :
Element is found at
index: 2
Explanation :
1. The code imports the java.util.Arrays package, which includes various utility methods for working with arrays, including the binarySearch method.2. The BinarySearchProgram class is defined with a main method, which is the entry point of the program.
3. An integer array arr is initialized with values {10, 20, 30, 40, 50}. Note that this array is sorted in ascending order.
4. The variable key is set to the value 30, which is the element we want to search for in the array.
5. The Arrays.binarySearch method is used to perform a binary search on the sorted array arr for the value specified by the key variable. The result of the search is stored in the result variable.
6. The code checks if the value of result is less than 0. If it is, this indicates that the key was not found in the array, and the code prints "Element is not found!".
7. If the value of result is greater than or equal to 0, it means that the key was found in the array, and the code prints "Element is found at index: " followed by the index at which the key was found in the array.
Comments
Post a Comment