1

该程序假设检测是否找到整数以及查找所需的时间。第一个是线性搜索,第二个是二分搜索。我遇到的问题是这样的。线性搜索有效,但我不断收到“线性搜索成功”的消息。老实说,我不确定为什么二进制搜索没有输出任何内容。任何帮助表示赞赏

public class search {

/**
 * @param args
 */
public static void main(String[] args) {
    Scanner scanner1 = new Scanner(System.in);
    System.out.println("Please enter in an integer:");
    int searchValue = scanner1.nextInt();

    int[] numbers = new int[1000];
    try {
        Scanner scanner = new Scanner(new File("numbers.txt"));
        for (int i = 0; i < 1000; i++) {
            numbers[i] = scanner.nextInt();
        }
    } catch (FileNotFoundException e) {
        System.out
                .println("A problem occurred reading the file numbers.txt");
        System.exit(0);
    }
    long time = System.nanoTime();
    int linear = linearSearch(numbers, searchValue);
    long end = System.nanoTime();
    System.out.println(end - time);
}

public static int linearSearch(int[] numbers, int searchValue) {
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] > searchValue)
            return -1;
        else if (numbers[i] == searchValue)
            return i;
        System.out.println("Linear search successful");

    }

    return -1;
}

public int binarySearch(int searchValue, int[] numbers) {
    long time = System.nanoTime();
    int low = 0;
    int high = numbers.length - 1;
    while (low <= high) {
        int middle = low + (high - low) / 2;
        if (numbers[middle] == searchValue) {
            System.out.println("Binary found");
            long end = System.nanoTime();
            System.out.println(end - time);
        }
        if (searchValue < numbers[middle])
            high = middle - 1;
        else if (searchValue > numbers[middle])
            low = middle + 1;
        else
            return middle;

    }
    return -1;
}
}
4

2 回答 2

0

这是因为您从不调用该binarySearch()函数。你只打电话linearSearch()

/* Call to linearSearch is here */
int linear = linearSearch(numbers, searchValue);

/* No call to binarySearch to put here */
于 2013-04-09T20:43:47.397 回答
0

System.out.println("Linear search successful") 将它放在 for 循环之外,并且要进行二进制搜索,您至少需要调用该函数。

于 2020-07-01T13:48:36.147 回答