当我运行程序时,它恰好通过了插入排序,但是当我使用二进制搜索询问您想在数组中搜索哪个数字时,程序静止不动,它不会终止或任何事情. 我相信这与我的扫描仪有关。我已经使用单独的扫描仪进行插入排序和二进制搜索解决了这个问题,但我不应该创建单独的扫描仪来使其工作,对吗?
import java.util.Scanner;
public class Search {
public static void main(String [] args){
Insertion insert = new Insertion();
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int low = 0, high = array.length - 1, mid = (low+high)/2;
int num =0;
int target = 0;
for(int i = 0; i < array.length; i++){
System.out.println("Enter a number: ");
num = input.nextInt();
array[i] = num;
}
insert.insertion_srt(array, array.length);
System.out.println("Your numbers sorted: ");
for(int a = 0; a < array.length; a++){
System.out.print(array[a]+" ");
}
System.out.println("\nWhich number do you want to look for?: ");
target = input.nextInt();
while(low<=high && array[mid] != target){
if(target > array[mid])
low = mid + 1;
else
high = mid -1;
}
if(low>high)
mid = -1;
System.out.println(mid);
input.close();
}
}