This document contains a binary search program in Java. It takes user input for the size of an integer array and sorted elements to populate the array. It then takes a search key as input and uses a binary search algorithm to check if the key is present in the array. The program outputs the location if found or nothing if not found.
This document contains a binary search program in Java. It takes user input for the size of an integer array and sorted elements to populate the array. It then takes a search key as input and uses a binary search algorithm to check if the key is present in the array. The program outputs the location if found or nothing if not found.
This document contains a binary search program in Java. It takes user input for the size of an integer array and sorted elements to populate the array. It then takes a search key as input and uses a binary search algorithm to check if the key is present in the array. The program outputs the location if found or nothing if not found.
PROGRAM import java.util.*; public class BinarySearch { public static void main(String[] args) { int[]a=new int[20]; System.out.println("Enter the size of array"); Scanner s=new Scanner(System.in); int n=s.nextInt(); System.out.println("Enter "+n+" sorted elements"); for(int i=0;i<n;i++) a[i]=s.nextInt(); System.out.println("Enter the element to be searched"); int sk=s.nextInt(); int l=0,h = n-1; while(l<h){ int mid=(l+h)/2; if(a[mid]==sk) { System.out.println(sk + " found at location " + (mid + 1)); break; } else if(a[mid]<sk) l=mid+1; else h=mid-1;
} } } OUTPUT Enter the size of array 5 Enter 5 sorted elements 20 30 40 50 60 Enter the element to be searched 50 50 found at location 4