I want to get the input from user and search the index.
我想从用户那里获得输入并搜索索引。
Can any one help me to do it? It would be appreciated. Thank you.
任何人都可以帮我做吗?我们将不胜感激。谢谢。
public class Main {
int[] array = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30};
public int binarySearch(int key, int l, int r) {
if (r < l) {
return -1;
}
int mid = (l + r) / 2;
if (key == array[mid]) {
return mid;
}
if (key < array[mid]) {
return binarySearch(key, l, mid - 1);
} else {
return binarySearch(key, mid + 1, r);
}
}
public static void main(String[] args) {
Main b = new Main();
for (int i = 2; i < 32; i += 2) {
System.out.println("Search for element " + i);
System.out.println("This element is found at " + b.binarySearch(i, 0, 14));
System.out.println("=======+============+=======+==============");
}
}
}
2 个解决方案
#1
import java.util.Scanner;
public class Main {
int[] array = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30};
public int binarySearch(int key, int l, int r) {
if (r < l) {
return -1;
}
int mid = (l + r) / 2;
if (key == array[mid]) {
return mid;
}
if (key < array[mid]) {
return binarySearch(key, l, mid - 1);
} else {
return binarySearch(key, mid + 1, r);
}
}
public static void main(String[] args) {
Main b = new Main();
System.out.println("input the element you want to search :");
Scanner in = new Scanner(System.in);
int i = in.nextInt();
System.out.println("Search for element " + i);
System.out.println("This element is found at " + b.binarySearch(i, 0, 14));
System.out.println("=======+============+=======+==============");
in.close();
}
}
#2
You can take User Input with Scanner class
您可以使用Scanner类进行用户输入
int input;
Scanner sc=new Scanner(System.in);
input=sc.nextInt();
then pass this input to your binarySearch()
method
然后将此输入传递给binarySearch()方法
#1
import java.util.Scanner;
public class Main {
int[] array = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30};
public int binarySearch(int key, int l, int r) {
if (r < l) {
return -1;
}
int mid = (l + r) / 2;
if (key == array[mid]) {
return mid;
}
if (key < array[mid]) {
return binarySearch(key, l, mid - 1);
} else {
return binarySearch(key, mid + 1, r);
}
}
public static void main(String[] args) {
Main b = new Main();
System.out.println("input the element you want to search :");
Scanner in = new Scanner(System.in);
int i = in.nextInt();
System.out.println("Search for element " + i);
System.out.println("This element is found at " + b.binarySearch(i, 0, 14));
System.out.println("=======+============+=======+==============");
in.close();
}
}
#2
You can take User Input with Scanner class
您可以使用Scanner类进行用户输入
int input;
Scanner sc=new Scanner(System.in);
input=sc.nextInt();
then pass this input to your binarySearch()
method
然后将此输入传递给binarySearch()方法