【发布时间】:2014-02-22 04:41:38
【问题描述】:
我正在尝试使二进制搜索正常工作。它应该询问您数组的大小,要输入数组的整数并搜索数组以找到您正在寻找的数字以及找到它需要多少次探测或以未找到的数字进行响应。我正在遵循该算法,但它要么以无限循环响应,要么根本不响应,因为它永远运行。有什么建议吗?
package assignment3;
import java.util.Scanner;
public class search{
public static void main(String[] arg){
Scanner range=new Scanner(System.in);
System.out.println("Pick your array size.");
int element=range.nextInt();
int[] array=new int[element];
Scanner array_list=new Scanner(System.in);
if(element<=0){
System.out.println("The array size you chose is not supported. You must chose again");
Scanner tryagain=new Scanner(System.in);
System.out.println("Try again");
element=tryagain.nextInt();
}
System.out.println("Now enter all the numbers in your array");
String list=array_list.nextLine();
String[] newlist=list.split("\\ ");
int lengthofarray=newlist.length;
for(int i=0; i<lengthofarray; i++){
array[i]=Integer.parseInt(newlist[i]);
System.out.println(i+" || "+array[i]);
}
Scanner linearSearch=new Scanner(System.in);
System.out.println("Pick a number to see if it is in the array and how many times it took to find it.");
int linear=linearSearch.nextInt();
Scanner linear2=new Scanner(System.in);
System.out.println("Now we will try the same thing with a binary search. Pick a number");
int binarysearch=linear2.nextInt();
int low=0;
int high=lengthofarray-1;
int middle;
while(low<=high){
middle=(low+high)/2;
if(array[middle]>binarysearch){
high=middle-1;
}
else if(array[middle]<binarysearch){
low=middle+1;
}
}
if(array[low]==binarysearch){
System.out.println("Your number is in the array.");
}
else{
System.out.println("your number is not in the array.");
}
}
}
【问题讨论】:
-
除了缺少
array[middle] == binarysearch的情况外,二分查找仅适用于已排序的数组。您需要先致电Arrays.sort(array)。