Sunday, February 19, 2017

MeteredLinearSearcher

// ===============================================================
// "BEGIN AT THE BEGINNING, and go on till you find the right key;
//  then stop."
//                 - KNUTH (The Art of Computer Programming 3 6.1)
// ===============================================================

class MeteredLinearSearcher<T extends Comparable<T>>
extends MeteredSearcher<T> {

  public int maneuver(T[] seq, T key, int from, int to) {
 
    int step = from < to ? 1 : -1;
    int i = from;

    while (tick() && i != to) {
      if (tick() && key.compareTo(seq[i]) == 0) {
        return i;
      }
      i += step;
      tick();
    }
    return tick() && key.compareTo(seq[i]) == 0 ? i : fail;
  }
}