/*
 * Searcher.java
 *
 * Created on 27. März 2008, 19:54
 */

/**
 *
 * @author hug
 */
public abstract class Searcher<E>
{
   public abstract boolean property (E e);
   // Postcondition: e == null returns false.

   public boolean existsProperty (E[] a)
   {
      assert a != null : "precondition";
      int i = 0;
      while (i < a.length && !property(a[i]))
      {
	 i++;
      }
      assert i >= a.length || property(a[i]) : "termination condition";
      return i < a.length;
   }
   
   public static int linearSearchKW1 (Object[] f, Object a)
   {
      int res = -1; // not found
      for (int i = 0; i < f.length; i++)
      {
	 if (f[i].equals(a))
	    return (res = i);
      }
      return res;
   }
   
   public static int linearSearchKW2 (Object[] f, Object a)
   {
      try
      {
	 int i = 0;
	 while (!f[i].equals(a)) i++;
	 return i;
      } 
      catch (IndexOutOfBoundsException ioobe)
      {
	 return -1; // not found
      }
   }   
   
   public static int linearSearchMHR (int[] numbers, int key)
   {
      boolean found = false;
      int i = 0;
      // Repeat while more elements in array:
      while (i < numbers.length && !found)
      {
	 // If the current element contains the key:
	 //		Return the index of the current element
	 if (numbers[i] == key) {
	    found = true;		// Found!
	 } else {
	    i++;			// Move to next element
	 }
      }
      assert (i >= numbers.length || found): "Error in linear search.";
      if (found)
	 return i;			// The key is in element numbers[i]
      else
	 return -1;			// The key is not found
   }
}   

