/**
 * OrderedSearch.java
 * <br>
 * A class to demonstrated linear search on a sorted array.
 * <br>
 * Created: Tue Feb 11 14:30:59 2003
 *
 * @author <a href="mailto:shapiro@cse.buffalo.edu">Stuart C. Shapiro</a>
 */

public class OrderedSearch {

    /**
     * Returns the index within the array a of the first occurrence of the int i,
     * or -1 if i does not occur in a.
     * <p> The search range is a[0 .. a.length-1].<p>
     * a is assumed to be sorted from lower to higher ints.
     *
     * @param a the sorted <code>int[]</code> to be searched.
     * @param i an <code>int</code> value to search for.
     * @return the index of the first occurrence of i in a,
     * or -1 if i does not occur in a.
     */
    public static int indexOf(int[] a, int i) {
	int j;
	for (j = 0; j < a.length; j++) {
	    if (a[j] == i) {return j;}
	    if (a[j] > i) {return -1;}
	}
	return -1;
    }

    /**
     * Tests the indexOf method.
     *
     */
    private static void test(int[] a, int i) {
	System.out.print(i + " is at position " + indexOf(a, i) + " of "
			 + "\t{" + a[0]);
	for (int j = 1; j < a.length; j++) {System.out.print(", " + a[j]);}
	System.out.println("}");
    }

    /**
     * Demonstrates linear search on a sorted array.
     *
     * @param args a <code>String[]</code> value
     */
    public static void main (String[] args) {
	int[] testarray = {2,4,25,43,43,46,54,54,85,285,541,564};
	test(testarray, 54);
	test(testarray, 1);
	test(testarray, 99);
	test(testarray, 999);
    } // end of main ()
    
    
}// OrderedSearch
