Class X - Term 01 - Array Program 09
Class X - Term 01 - Array Program 09
QUESTION
Write a program in Java to accept an array of 'n' elements from the user. Accept an element
from the user to be searched in the array using the Binary Search technique.
(Hint: For performing Binary Search, the elements are accepted in ascending order).
CODE
import java.io.*;
import java.lang.*;
import java.util.*;
class Array9
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the array size : ");
int n = sc.nextInt( );
int arr[] = new int[n];
int l = 0, u= n-1;
int pos = 0;
boolean flag = false;
while(l <= u)
{
int mid = (l + u) / 2;
if(arr[mid] == key)
{
pos = mid + 1;
flag = true;
break;
}// end of if
if(arr[mid] < key)
{
l = mid + 1;
}// end of if
if(flag == true)
{
System.out.println("Element " + key + " is present in the array");
System.out.println("Element is present at position " + pos);
}// end of if
else
{
System.out.println("Element " + key + " is not present in the array");
}// end of else
}// end of main
}// end of class
OUTPUT