// This program demonstrates the use of a binary search method that returns an // indication of the insertion point for data not yet in a sorted array. import java.util.*; public class BinarySearch { public static void main(String[] args) { int[] data = new int[20]; Random r = new Random(); for (int i = 0; i < data.length; i++) { data[i] = r.nextInt(50); } Arrays.sort(data); System.out.println("data = " + Arrays.toString(data)); for (int i = 0; i < 20; i++) { System.out.println("index of " + i + " = " + binarySearch(data, i)); } } // pre : list is sorted // post: returns the index of where value appears in the given array; // returns -(insertion point) - 1 if not found public static int binarySearch(int[] list, int value) { int low = 0; int high = list.length - 1; while (low <= high) { int mid = (low + high) / 2; if (list[mid] == value) { return mid; } else if (list[mid] < value) { low = mid + 1; } else { high = mid - 1; } } return -low - 1; } }