二进制和线性搜索

时间:2013-04-09 20:38:30

标签: java binary-search linear-search

该程序假设检测是否找到整数以及找到它需要多长时间。第一个是线性搜索,第二个是二分搜索。我遇到的问题是这个。线性搜索工作,除了我一次又一次地收到消息“线性搜索成功”。我不确定为什么二进制搜索没有输出任何诚实的东西。任何帮助表示赞赏

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

2 个答案:

答案 0 :(得分:0)

这是因为你从不调用binarySearch()函数。您只需拨打linearSearch()

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

/* No call to binarySearch to put here */

答案 1 :(得分:0)

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