我想从用户获取用户输入并进行非递归二进制搜索,任何人都可以向我展示如何做到这一点。
public class Main {
// binarySeach: non-recursive
public int Main(int[] a, int x) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high)/2;
if (a[mid] == x) return mid;
else if (a[mid] < x) low = mid + 1;
else high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
Main bin = new Main();
int[] a =
{ 2, 8,12,14,16,19,24,28,31,33,// 0-9
39,40,45,49,51,53,54,56,57,60,// 10-19
63,69,77,82,88,89,94,96,97}; // 20-28
for (int i = 0; i < a.length; i++)
System.out.print(bin.Main(a,
a[i]) + " ");
System.out.println();
}
}
public static void main(String[] args) {
Main bin = new Main();
int[] a = { 2, 8,12,14,16,19,24,28,31,33,// 0-9
39,40,45,49,51,53,54,56,57,60,// 10-19
63,69,77,82,88,89,94,96,97}; // 20-28
Scanner userinput = new Scanner(System.in);
System.out.println("Enter number to search");
int n = userinput.nextInt();
System.out.println("Number index: "+bin.Main(a, n));
}
通知第一个位置/索引为0,因此,如果要获得数字12而不是索引2的数字索引3,请将System.out.println("Number index: "+bin.Main(a, n));
更改为System.out.println("Number index: "(bin.Main(a, n)+1));
从我所理解的内容中,您想在数组中搜索一个输入的值并返回其索引。
因此,您首先需要从用户输入中获取值,然后像这样在数组中搜索它:
public class Main {
public int Search(int[] a, int x) {
int low = 0;
int high = a.length - 1;
Boolean search=false;
while (low <= high && !search) {
int mid = (low + high)/2;
if (a[mid] == x) {
search=true;
return mid;
}
else if (a[mid] < x) low = mid + 1;
else high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
Main bin = new Main();
int[] a ={ 2, 8,12,14,16,19,24,28,31,33,// 0-9
39,40,45,49,51,53,54,56,57,60,// 10-19
63,69,77,82,88,89,94,96,97}; // 20-28
Scanner input = new Scanner(System.in);
System.out.println("Enter the number you whould like to search !");
int n=input.nextInt();
int index=bin.Search(a,n);
if(index<0) { //-1 means that the element doesn't exist in the array
System.out.println("This number doesn't exist in the array ");
} else { //The "}" before the else was missing
System.out.println("The index of the number "+n+" in the array is :"+ index);
}
}
}
您需要使用 Scanner
来获取用户输入,而无需循环数组即可搜索它,您只需要调用搜索方法并将array
和inputted value
传递为参数。
编辑:
请参阅LIVE DEMO 在此处,输入为8
,INEEX为1
。