//Program to create a binary search using recursion.
import java.util.*;
class B_Search
{
int ar[];
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no . of elements");
int l=sc.nextInt();
ar=new int[l];
for(int i=0;i<l;i++)
ar[i]=sc.nextInt();
System.out.println("Enter the element to be searched");
int s=sc.nextInt();
System.out.println("Element found at " + search(0,l-1,s));
}
public int search(int lp,int up,int s)
{
int mid=(up+lp)/2;
if(ar[mid]==s)
return (1+mid);
else if(ar[mid]>s)
return search(lp,mid-1,s);
else
return search(mid+1,up,s);
}
}
No comments:
Post a Comment
Convey your thoughts to authors.