The document contains a Java program that implements a binary search algorithm. It prompts the user to input the size of an array, the elements of the array, and a value to search for. The program then searches for the value using binary search and outputs the index if found or a message if not found.
The document contains a Java program that implements a binary search algorithm. It prompts the user to input the size of an array, the elements of the array, and a value to search for. The program then searches for the value using binary search and outputs the index if found or a message if not found.
import java.util.*; class BinarySearch { public static void main() { Scanner sc = new Scanner(System.in); System.out.println(“Enter the index of array”); int n = sc.nextInt(); int arr[] = new int[n];
int i, first, last, mid, key;
System.out.println(“Enter the elements of array”);
for(i=0; i<n; i++) { arr[i] = sc.nextInt(); }
System.out.println(“Enter the value to search”);
key = sc.nextInt;
mid = (first + last)/2;
while( first <= last ) { if ( arr[mid] == key ) { System.out.println("Element is found at index: " + mid); break; } else if ( arr[mid] < key ) { first = mid + 1; } else { last = mid - 1; } mid = (first + last)/2; }
if ( first > last )
{ System.out.println("Element is not found!"); } } }