OneCompiler

BINARY SEARCH : SEARCH AN ELEMNT FROM 'n' NUMBER OF ELEMENTS

277

Define a class to declare an integer array of size 'n' and accept the elements into the array in ascending order. Search for an element input by the user using binary search technique , display the element if it is found , otherwise display the message "NO SUCH ELEMENT".

import java.util.*;

public class Main {
public static void main(String[] args) {
int flg=0, L=0,M=0,n;
Scanner sc = new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF ELEMENTS " );
n = sc.nextInt();
int U = n-1;
int a[] = new int[n];
System.out.println("ENTER THE ELEMENTS IN ASCENDING ORDER");
for(int i= 0 ; i<n; i++)
a[i] = sc.nextInt();
System.out.println("DISPLAYING THE ELEMENTS : " );
for(int i=0 ; i<n; i++)
System.out.print(a[i]+"\t");
System.out.println("ENTER THE ELEMENT TO BE SEARCHED : ");
int sr = sc.nextInt();
if(L<=U)
{
M = (U+L)/2;
if(sr>a[M])
U= M-1;
else
if(sr<a[M])
L= M+1;
else
{
System.out.println("ELEMENT FOUND @ " + (M+1));
flg =1;

  }
}
if(flg==0)
System.out.println("NO SUCH ELEMENT");
}

}

FOR CODE,
CLICK : https://onecompiler.com/java/3xywtgtpq (TO FIND OUTPUT)