public class Searching {
  /** search for int i in list l 
   *   return the index of the position if found, 
   *  otherwise, return -1
   */
  public static int linearSearch(int i, int [] tbl) {
    for (int j = 0; j < tbl.length; j++) {
      if (i == tbl[j] ){
        return j;
      }
    }
    // we have fallen out of the loop without finding i, therefore we
    // must return the failure value.
    return -1;
  }
  
  /** 
   * Check to see if an integer is in a sorted list.
   * If so, return the position in the list as an integer,
   * otherwise, return -1.
   */
  public static int binarySearch(int i, int [] tbl) {
    int beg = 0;
    int end = tbl.length - 1;
    // if the beginning is set after the end, then we know that
    // i is not in our list.  Why?
    while (beg <= end) { 
      //First determine the halfway point in our list
      int mid = (beg + end) / 2;
      // is i the value at the midpoint?
      if (tbl[mid] == i) {
        return mid;
      }
      if (tbl[mid] > i)  {
        // if the midpoint is greater than i, then everything at or
        // after the midpoint is greater than i.  Therefore we can ignore
        // it.  We do this by setting the new end to the list at the position
        // just prior to the midpoint.
        end = mid - 1;
      } else {
        // Otherwise, midpoint must be less than i, then everything at or
        // before the midpoint is less than i.  Therefore we can ignore
        // it.  We do this by setting the new beginning of the list at the position
        // just after the midpoint.
        beg = mid + 1;
      }
    }
    // we have fallen out of the loop without finding i, therefore we
    // must return the failure value.
    return -1;
  }
    /**
     * Display the contents of the list.
     */
    public static void displayList(int [] list) {
      for ( int i = 0; i< list.length; i++) {
        System.out.print(list[i] + " ");
      }
      System.out.println();
    }
  }
  
