// This class shows an example of how to use binary search import java.util.Arrays; public class BinarySearch { public static void main(String[] args) { int[] arr = {-4, 2, 7, 10, 15, 20, 22, 25, 30, 36, 42, 50, 56, 68, 85, 92, 103}; System.out.println("Our binary search: " + binarySearch(arr, 42)); System.out.println("Java's binary search: " + Arrays.binarySearch(arr, 42)); } // pre: The array is sorted // post: Returns the index of the first occurence of val in arr, -1 if not found public static int binarySearch(int[] arr, int val) { int low = 0; int high = arr.length - 1; // Keep going while the high and low pointers haven't moved past each other while(high >= low) { int middle = (low + high) / 2; if (arr[middle] == val) { return middle; // we found it! } else if (arr[middle] < val) { low = middle + 1; } else { // arr[middle] > val high = middle - 1; } } return -1; // not found } }