mercredi 3 juin 2015

Random Number Array using binarySearch and Linear Search

I am trying to create an array in my main class which uses a random number and then will use both binary and linear search to return that number and the time it took for both to determine which would be faster. While trying to develop the array the Random method keeps coming up as invalid and I am not sure how to implement the binary Search.

public class Search {

public static boolean binarySearch(int[] array, int value) {
    return binarySearchHelper(array, value, 0, array.length);
}

private static boolean binarySearchHelper(int[] array, int value, int low, int high) {
    if (low <= high) {
        int mid = (low + high) / 2;
        if (value == array[mid]) {
            return true;
        } else if (value < array[mid]) {
            return binarySearchHelper(array, value, low, mid - 1);
        } else {
            return binarySearchHelper(array, value, mid + 1, high);
        }
    }
    return false;
}

public static boolean linearSearch(int[] array, int value) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == value) {
            return true;
        } else if (array[i] > value) {
            return false;
        }
    }
    return false;
}

}

public class Test {

public static void main(String[] args) {

    //System.nanoTime() will give me the current time (it's like looking at the clock)
    //I'll save the current time right (immediately) before I start the thing I want to time
    long start = System.nanoTime();
    for (int i = 0; i < 100000; i++) {
        System.out.println(i);
    }
    //immediately after the thing I am timing is done, I'll look at the clock again
    //in this case, I'll calculate the elapsed time.
    long elapsed = System.nanoTime() - start;
    System.out.println("That pointless loop took: " + elapsed + " nano seconds");
    public static int random(int min, int max){
    int size = 2000;
    int max = 5000;
    int[] array = new int[size];
    int loop = 0;

    Random rand = new Random();
    int value = rand.nextInt(2001);
    for (int i = 0; i < size; i++) {
        array[i].nextInt(max);
    }

}

}




Aucun commentaire:

Enregistrer un commentaire