// Play with some searching // Beth Katz - April 2009 public class Search1 { public static void main(String[] args) { // initialize arrays int[] bumpy = {79, 45, 67, 92, 93, 35, 78, 93, 89, 67, 78}; int[] smooth = {82, 86, 84, 85, 83, 84, 85, 83}; print(bumpy, "Bumpy"); printSearch(bumpy, 92); printSearch(bumpy, 42); print(smooth, "Smooth"); printSearch(smooth, 84); } // linear search for target in list; return index if found // return -1 if not found public static int linearSearch(int[ ] list, int target) { for (int i = 0; i < list.length; i++) { if (list[i] == target) { return i; // found it; return index } } return -1; // didn't find it } // prints results of searching for target in list public static void printSearch(int[ ] list, int target) { int answer = linearSearch(list, target); if (answer >= 0) { System.out.println("Found " + target + " at " + answer); } else { System.out.println("Didn't find " + target); } } // prints a list with items separated by spaces // ------- uses for-each loop ----------- // for ( : ) { public static void print(int[] list, String label) { System.out.print(label + " has " + list.length + " items: "); for (int item : list) { System.out.print(item + " "); } System.out.println( ); } } /****** output ****** Bumpy has 11 items: 79 45 67 92 93 35 78 93 89 67 78 Found 92 at 3 Didn't find 42 Smooth has 8 items: 82 86 84 85 83 84 85 83 Found 84 at 2 *********************/