如何向此代码添加用户输入并使用递归算法进行搜索?

时间:2015-05-06 08:32:19

标签: java binary-search

我想从用户那里获得输入并搜索索引。

任何人都可以帮我做吗?我们将不胜感激。谢谢。

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 个答案:

答案 0 :(得分:0)

您可以使用Scanner class

进行用户输入
int input;
Scanner sc=new Scanner(System.in);
input=sc.nextInt();

然后将此输入传递给您的binarySearch()方法

答案 1 :(得分:0)

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();
    }
}