/** * LinearSearch.java *
* A class to demonstrate linear search. *
* Created: Tue Feb 11 14:30:59 2003 * * @author Stuart C. Shapiro */ public class LinearSearch { /** * Returns the index within the array a of the first occurrence of the int i, * or -1 if i does not occur in a. *

The search range is a[0 .. a.length-1]. * * @param a the int[] to be searched. * @param i an int 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) { for (int j = 0; j < a.length; j++) { if (a[j] == i) {return j;} } 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. * * @param args a String[] value */ public static void main (String[] args) { int[] testarray = {54,85,25,4,564,2,46,2,43,2,541,285}; test(testarray, 2); test(testarray, 10); } // end of main () }// LinearSearch