Search code examples
javabinary-searchlinear-search

Binary and Linear search


This program is suppose to detect if an integer is found or not and how long it took to find. The first one is a linear search and the second is a binary search. The problems I'm having is this. The linear search works, except I keep getting the message "Linear search successful" again and again. I'm not sure why the binary search isn't outputting anything to be honest. Any help is appreciated

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

Solution

  • It's because you never call the binarySearch() function. You only call linearSearch().

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