Sunday, February 12, 2017

Sequential searching classes

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

public class MeteredLinearSearch<T extends Comparable<T>>
extends MeteredSearch<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;
  }
}
 
public class MeteredQuickLinearSearch<T extends Comparable<T>>
extends MeteredSearch<T> {

  public int maneuver(T[] seq, T key, int from, int to) {

    // Put an Elephant in Cairo, to wit
    // put the key in the last place you'd look.
 
    int step = from < to ? 1 : -1;
    T bumpedValue = seq[to];
    seq[to] = key;

    int i = from;
    while (tick() && key.compareTo(seq[i]) != 0) {
      i += step;
      tick();
    }
    seq[to] = bumpedValue;
    return tick() && key.compareTo(seq[i]) == 0 ? i : fail;
  }
}
 
public class MeteredQuickerLinearSearch<T extends Comparable<T>>
extends MeteredSearch<T> {

  public int maneuver(T[] seq, T key, int from, int to) {

    // Look twice before you leap two steps.
 
    int step = from < to ? 1 : -1;
    int leap = 2 * step;
    T bumpedValue = seq[to];
    seq[to] = key;

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