public class Search {
  
  /**
   * Find the location of x in the list and return
   * the index.  If x is is not in the list, then return -1.
   * 
   * @param list A list of integers.
   * @param x The element to search for.
   */ 
  public static int linearSearch(int[] list, int x) {
    
    for (int i = 0; i < list.length; i++) {
      if (list[i] == x) {
        return i;
      }
    }
    
    return -1;
  }
  
  /**
   * Find the location of x in the list and return
   * the index.  If x is not in the list, then return -1.
   * 
   * @param list A list of integers sorted in ascending order.
   * @param x The element to search for.
   */ 
  public static int binarySearch(int[] list, int x) {
    int beg = 0;
    int end = list.length - 1;
    int mid;
    
    while (beg <= end) {
      mid = (beg + end) / 2;
      
      if (list[mid] < x) { // means that x might be in [mid+1..end]
        beg = mid + 1;
      } else if (list[mid] > x) { // means that x might be in [beg..mid-1]
        end = mid - 1;
      } else { // means that x is found!
        return mid;
      }
    }
    
    return -1;
  }   
}
