K.E.
CARMEL GROUP OF SCHOOLS
2021–2022
COMPUTER TERM–01
CLASS–X 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;
System.out.println("Enter the array elements in ascending order : ");
for(int i=0; i<arr.length; i++)
{
System.out.print("arr[" + i + "] = ");
arr[i] = sc.nextInt( );
}// end of for
System.out.print("\nEnter the element to be searched : ");
int key= sc.nextInt( );
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(arr[mid] > key)
{
u = mid - 1;
}// end of if
}// end of while
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