This is a Java program that implements binary search to find the position of a given element in a sorted array of integers. The program initializes an array of integers named a with 10 elements in ascending order. It then prompts the user to enter an integer to search for.
The binary_search function is defined to take an array, a, and the indices of the first and last elements of the subarray to be searched, as well as the item to be searched for. The function first checks if the subarray to be searched is not empty. If it is not empty, it calculates the middle index of the subarray using the formula (low + high) / 2, where low and high are the indices of the first and last elements of the subarray, respectively.
If the middle element of the subarray is equal to the item being searched for, the function returns the index of the middle element. If the middle element is greater than the item, the function recursively calls itself with the lower half of the subarray. Otherwise, the function recursively calls itself with the upper half of the subarray. The function returns -1 if the item is not found in the subarray.
The main function prompts the user to enter an item to search for and calls the binary_search function with the array, the indices of the first and last elements of the array, and the item to search for. If the item is found, the function prints the position of the item. Otherwise, it prints "Item Not Found".
import java.util.Scanner; public class Binary_Search { public static int binary_search(int a[], int low, int high, int item) { if (high >= low) { int mid = low + (high - low) / 2; if (a[mid] == item) return mid; if (a[mid] > item) return binary_search(a, low, mid - 1, item); return binary_search(a, mid + 1, high, item); } return -1; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int i = 0; int n = 0; int a[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; int item = 0; int pos = 0; for(i=0;i<a.length;i++) { System.out.print(a[i]+" "); } System.out.print("\nEnter Item to Search : "); item = input.nextInt(); pos = binary_search(a, 0, a.length, item); if (pos == -1) { System.out.println("Item Not Found"); } else { System.out.printf("Item Found at %d Position", pos); } } }
10 20 30 40 50 60 70 80 90 100 Enter Item to Search : 60 Item Found at 5 Position
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions