OneCompiler

BINARY SEARCH : SEARCH A NUMBER

199

Write a program to search for a number in an array of seven integers using binary search technique .

import java.util.*;

public class binarySearch {
public static void main(String[] args) {
int flg= 0, L=0, U=6, M=0;
Scanner sc = new Scanner (System.in);
System.out.println("ENTER 7 INTEGERS:");
int a[] = new int [7];
for(int i = 0 ; i<7; i++)
a[i] = sc.nextInt();
System.out.println("DISPLAYING ARRAY ELEMENTS : " );
for(int i=0; i<7;i++)
System.out.print(a[i]+"\t");
System.out.println("ENTER SEARCH ELEMENT : ");
int sr = sc.nextInt();
while(L<=U)
{
M = (L+U)/2;
if(sr>a[M])
L= M+1;
else if(sr<a[M])
U=M-1;
else
{
System.out.println("FOUND VALUE @ : " + (M+1));
flg= 1;
break;
}
}
if(flg == 0)
System.out.println(" NOT FOUND ");
}
}

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