I have created the array and a method to sort the array, but I am still stuck on how to implement the binary search method in the array. Also the binary search method needs to be called from the array in the main class.
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;
}
And Here is the Main
import java.util.Random;
import java.util.Arrays;
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();
long elapsed = System.nanoTime() - start;
Random value = new Random();
int size = 2000;
int max = 5000;
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = value.nextInt();
}
Arrays.sort(array);
for (int i = 100; i < 2000; i+=100) {
start = System.nanoTime();
for ( int j = 0; j < 2000; j++){
Search.binarySearch(array, value.nextInt());
}
}
elapsed = System.nanoTime() - start;
System.out.println("Total time elapsed is: "+ elapsed);
}
}