Recursive program to perform the Binary search technique.
Recursive program to perform the Binary search technique.
import java.util.*;
class BS{
static int a[];
public void check(int lb,int ub,int s){
if(lb>ub)
System.out.println("NOT FOUND");
else
{
int m=(lb+ub)/2;
if(a[m]==s)
System.out.println(s+" Found at "+(m+1)+"th position");
else
if(s>a[m])
check(m+1,ub,s);
else
check(lb,m-1,s);
}
}
public static void main(){
Scanner sc=new Scanner(System.in);
int i,n;
System.out.println("Enter size of array");
n=sc.nextInt();
System.out.println("Enter "+n+" numbers in array in ascending order");
a=new int[n];
for(i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("Enter search element");
BS b=new BS();
b.check(0,n-1,n=sc.nextInt());
}
}
OUTPUT---
Enter size of array
6
Enter 6 numbers in array in ascending order
1
2
3
4
5
6
Enter search element
4
4 Found at 4th position
import java.util.*;
class BS{
static int a[];
public void check(int lb,int ub,int s){
if(lb>ub)
System.out.println("NOT FOUND");
else
{
int m=(lb+ub)/2;
if(a[m]==s)
System.out.println(s+" Found at "+(m+1)+"th position");
else
if(s>a[m])
check(m+1,ub,s);
else
check(lb,m-1,s);
}
}
public static void main(){
Scanner sc=new Scanner(System.in);
int i,n;
System.out.println("Enter size of array");
n=sc.nextInt();
System.out.println("Enter "+n+" numbers in array in ascending order");
a=new int[n];
for(i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("Enter search element");
BS b=new BS();
b.check(0,n-1,n=sc.nextInt());
}
}
OUTPUT---
Enter size of array
6
Enter 6 numbers in array in ascending order
1
2
3
4
5
6
Enter search element
4
4 Found at 4th position
Comments
Post a Comment