You are here: Home Demos Lecture 14 LinearSearch.java

LinearSearch.java

Plain Text icon LinearSearch.java — Plain Text, 576 bytes

File contents

public class LinearSearch {

    /*@ requires array != null;
      @ ensures 
      @   (\exists int j; 0 <= j && j < array.length; array[j] == elem) ?
      @     array[\result] == elem : \result == -1;
      @*/
    public int search(int[] array, int elem) {
        /*@ loop_invariant i >= 0;
          @ loop_invariant !(\exists int j; 0 <= j && j < i; array[j] == elem);
          @ decreases array.length - i;
          @*/
        for (int i = 0; i < array.length; i++) {
            if (array[i] == elem)
                return i;
        }
        return -1;
    }
}