【发布时间】:2020-01-30 20:23:43
【问题描述】:
我正在使用 List 来动态存储值,但我必须在输入二进制搜索程序之前指定 List 的大小。 我需要帮助,因为我不想将大小作为输入。
我尝试使用length,但不起作用,有人建议我使用size(),但我不知道如何使用。
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");
}
}
}
}
现在我希望用户输入元素直到他想要,然后使用二分搜索找到元素的索引
【问题讨论】:
-
如果你不想让用户指定他想要输入的元素数量,你希望他如何指示他已经输入了所有元素?
-
您可以读取数字,直到用户输入转义数字。然后使用
L.get(L.size() - 1);而不是L.get(n-1); -
如果我们将 0 声明为转义元素,那么用户将无法在其间输入 0,因此我们不能使用任何数字作为转义元素。@SomeFire
-
字符串
end怎么样?您需要将数字输入多行,或者您可以将单行输入视为数字数组并用空格或其他分隔符将其拆分(因此无需输入结尾,它将是输入键)
标签: java search arraylist binary-search