Binary Search
Write a program to search an element from the array using binary search technique.
Write a program to search an element from the array using binary search technique.
import java.io.*;
public class binary
{
int a[];
int u,l,n,m;
binary(int nn)
{
n=nn;
a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=0;
}
l=0;
u=n-1;
}
void readdata()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the elements");
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
}
int binary_search(int v)
{
m=-1;
while(u<=n-1)
{
m=(l+u)/2;
if(a[m]>v)
{
u=m-1;
m=binary_search(v);
}
else if(a[m]<v)
{
l=m+1;
m=binary_search(v);
}
else
break;
}
return m;
}
void display()
{
if(m==-1)
System.out.println("the element is absent");
else
System.out.println("the element is on "+m+" index");
}
public static void main()throws IOException
{
binary obj=new binary(6);
obj.readdata();
obj.binary_search(4);
obj.display();
}
}Related Posts
Continue learning with these related articles

String Methods in Java for ICSE Class 10: 25 Output Questions with Answers
ICSE Class 10 Computer Applications practice on String class methods: length, charAt, indexOf, lastIndexOf, substring, replace, trim, compareTo, equals and more, with 25 board-style output questions and step-by-step answers.

Special Number Programs in Java for ICSE: Armstrong, Spy, Neon, Disarium, Pronic and More
Every special number asked in ICSE Computer Applications – prime, perfect, Armstrong, palindrome, automorphic, neon, spy, Niven, duck, buzz, Disarium, special and pronic numbers – with definitions, examples and one complete Java program that checks them all.

Math Library Methods in Java for ICSE Class 9 (with Outputs)
ICSE Class 9 Computer Applications notes on the Java Math class: sqrt, cbrt, pow, abs, max, min, ceil, floor, round, rint and random, with return types, tricky negative-number outputs and Java expressions for formulas.