I am using List for dynamically storing the values, but I have to specify the size of List before taking input in the Binary search program. I want help in that I don't want to take size as an input.
I have tried using length
but that doesn't work, someone suggested me to use size()
, but I don't know how to use it.
import java.util.*;
class Binary
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter size of array");
int n=s.nextInt();
System.out.println("Enter array elements in ascending order");
List<Integer> L=new ArrayList<>();
for(int i=0;i<n;i++)
{
int e=s.nextInt();
L.add(e);
}
System.out.println("Enter the element you want to search");
int h=s.nextInt();
int left=L.get(0);
int right=L.get(n-1);
while(left<=right)
{
if(h<=right){
int m=(left+right)/2;
if(m==h)
{
System.out.println("Element found at index:"+L.indexOf(m)+" starting from 0");
return;
}
if(m>h)
{
right=m-1;
}
if(m<h)
{
left=m+1;
}
}
else{
System.out.println("Element not present");
}
}
}
}
Now I am expecting the user to enter elements till he desires and then to find index of element using Binary Search