UNB/ CS/ David Bremner/ teaching/ java/ Bsearch.java
import ccj.*;

public class Bsearch
{  public static void main(String[] args)
   {  int[] v = new int[20];
      int i;
      v[0] = 1;
      for (i = 1; i < v.length; i++)
         v[i] = v[i - 1] + Numeric.randomInt(1, 10);
      print(v);
      System.out.print("Enter number to search for: ");
      int n = Console.in.readInt();
      int j = binarySearch(v, 0, v.length - 1, n);
      System.out.println("Found in position " + j);
   }

   public static int binarySearch(int[] v, int from,
      int to, int a)
   {  if (from > to)
         return -1;
      int mid = (from + to) / 2;
      int diff = v[mid] - a;
      if (diff == 0) /* v[mid] == a */
         return mid;
      else if (diff < 0) /* v[mid] < a */
         return binarySearch(v, mid + 1, to, a);
      else
         return binarySearch(v, from, mid - 1, a);
   }

   public static void print(int[] a)
   {  int i;
      for (i = 0; i < a.length; i++)
         System.out.print(a[i] + " ");
      System.out.println();
   }
}