在java中使用线性和二进制搜索的用户输入
Posted
技术标签:
【中文标题】在java中使用线性和二进制搜索的用户输入【英文标题】:User input with linear and binary searching in java 【发布时间】:2014-01-29 23:50:19 【问题描述】:我正在尝试编写一个程序,要求用户输入用户想要创建的数组的大小,然后要求用户用元素填充数组,然后它应该显示数组及其元素并且,要求用户搜索一个整数。它应该进行线性和二进制搜索,同时显示确定元素是否在数组中所需的探测次数。到目前为止,我得到的唯一输出是尚未找到该元素。如果您可以查看我的代码并了解问题所在,因为我已经尝试了几个小时并且我已经改变了我能想到的一切。任何帮助将不胜感激。
import java.util.Scanner;
public class Searching
public static int[] anArray = new int[100];
private int numberOfElements;
public int arraySize = numberOfElements;
public String linearSearch(int value)
int count = 0;
boolean valueInArray = false;
String indexOfValue = "";
System.out.print("The Value was Found in: ");
for(int i = 0; i < arraySize; i++)
if(anArray[i] == value)
valueInArray = true;
System.out.print(i + " ");
indexOfValue += i + " ";
count ++;
if(!valueInArray)
indexOfValue = " None found";
System.out.print(indexOfValue);
System.out.println("\nIt took " + count + " probes with a linear search to find");
return indexOfValue;
public void binarySearch(int value)
int min = 0;
int max = arraySize - 1;
int count = 0;
while(min <= max)
int mid = (max + min) / 2;
if(anArray[mid] < value) min = mid + 1;
else if(anArray[mid] > value) max = mid - 1;
else
System.out.println("\nFound a Match for " + value + " at Index " + mid);
min = max + 1;
count ++;
System.out.println("It took " + count + " probes with a binary search to find");
public static void main(String[] args)
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("Input the number of elements in your Array");
int numberOfElements = scan.nextInt();
if(numberOfElements <= 0)
System.exit(0);
int[] anArray = new int[numberOfElements];
System.out.println("\nEnter " + numberOfElements + " Integers");
for(int i = 0; i < anArray.length; i ++)
System.out.println("Int # " + (i + 1) + ": ");
anArray[i] = scan.nextInt();
System.out.println("\nThe integers you entered are: ");
for(int i = 0; i < anArray.length; i ++) // for loop used to print out each element on a different line
System.out.println(anArray[i]);
System.out.println("Which element would you like to find?");
int value = scan.nextInt();
Wee3Q2JOSHBALBOA newArray = new Wee3Q2JOSHBALBOA();
newArray.linearSearch(3);
newArray.binarySearch(value);
【问题讨论】:
【参考方案1】:嗯,我不确定您是否以正确的方式使用数组,您会看到数组是固定大小的,我认为您不能像他们那样扩展...
尝试将数组的大小设置为特定长度。 或者使用向量
【讨论】:
以上是关于在java中使用线性和二进制搜索的用户输入的主要内容,如果未能解决你的问题,请参考以下文章