我使用我的第一个二进制搜索技术犯了一个简单的错误吗?

时间:2016-02-26 04:24:59

标签: java arrays random foreach binary-search

我创建了一个数组,在1-100之间生成10个随机数,用for循环排序(假设使用"增强for循环")。除了使我的for循环增强之外,剩下的最后一件事是"输入一个值,使用二进制搜索技术搜索数组以确定是否存在值并输出。你看到了什么问题吗?谢谢!

import java.util.*;

class lab4point2 //lab4.2 part 1 {
    public static void main(String args[]) {
        int[] array = new int[10]; //array of 10 numbers created.
        Random rand = new Random(); //random class created called rand.

        for (int cnt = 0; cnt < array.length; cnt++) { //for loop to generate
            array[cnt] = rand.nextInt(100) + 1;     // the 10 numbers randomly 1-100
        }
        Arrays.sort(array); //sorted
        System.out.println(Arrays.toString(array));// prints the 10 numbers to screen

        System.out.print("Enter a value to see if it is present. ");
        Scanner scanner = new Scanner(System.in);
        int value = scanner.nextint();

        boolean binarySearch(array, 0, 99, value);
        int size = 100;
        int low = 0;
        int high = size - 1;

        while (high >= low) {
            int middle = (low + high) / 2;
            if (data[middle] == value) {
                System.out.print("Value is present ");
                return true;
            }
            if (data[middle] < value) {
                low = middle + 1;
            }
            if (data[middle] > value) {
                high = middle - 1;
            }
       }
       System.out.print("Value is not present. ");
       return false;
   }
}

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些语法错误。它应该看起来更像是:

class SearchArray {
    private final int[] array = new int[10];
    private final Random random = new Random();

    public SearchArray() {
        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(100) + 1;
        }
        Arrays.sort(array);
    }

    public String toString() {
        return Arrays.toString(array);
    }

    public boolean contains(int value) {
        int low = 0;
        int high = array.length - 1;

        while (high >= low) {
            int middle = (low + high) / 2;
            if (array[middle] == value) {
                return true;
            }
            if (array[middle] < value) {
                low = middle + 1;
            }
            if (array[middle] > value) {
                high = middle - 1;
            }
        }
        return false;
    }          

class lab4point2 {
    public static void main(String args[]) {
        SearchArray array = new SearchArray();
        System.out.println(array.toString());

        System.out.print("Enter a value to see if it is present. ");
        Scanner scanner = new Scanner(System.in);
        int value = scanner.nextint();
        if (array.contains(value)) {
            System.out.print("Value is present. ");
        } else {
            System.out.print("Value is not present. ");
        }
    }
}