Binary Search in java
Time Complexity for Binary Search will be Log(n). But the main Condition is, the inputted elements in the array must be sorted (ascending order).
import java.util.*;
class BSearch
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=s.nextInt();
System.out.println("enter the element to be find");
int f=s.nextInt();
int k=bs(a,0,n-1,f);
if(k==-1)
System.out.println("the element not present");
else
System.out.println("the element is at index "+(k+1));
}
static int bs(int a[],int st,int en,int f)
{
if(en>=st)
{
int mid=(st+en)/2;
if(a[mid]==f)
return mid;
else if(a[mid]<f)
return bs(a,mid+1,en,f);
else
return bs(a,0,mid-1,f);
}
return -1;
}
}
import java.util.*;
class BSearch
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=s.nextInt();
System.out.println("enter the element to be find");
int f=s.nextInt();
int k=bs(a,0,n-1,f);
if(k==-1)
System.out.println("the element not present");
else
System.out.println("the element is at index "+(k+1));
}
static int bs(int a[],int st,int en,int f)
{
if(en>=st)
{
int mid=(st+en)/2;
if(a[mid]==f)
return mid;
else if(a[mid]<f)
return bs(a,mid+1,en,f);
else
return bs(a,0,mid-1,f);
}
return -1;
}
}
Comments
Post a Comment