Source of LinearSearch.java



  3: import java.util.Scanner;

  5: /**
  6:  *
  7:  * @author Mark Young (A00000000)
  8:  */
  9: public class LinearSearch {

 11:     public static final Scanner KBD = Common.KBD;
 12:     private static final int HOW_MANY = 40;
 13:     private static final int MAX = 100;
 14:     private static int traceLevel = 0;

 16:     public static void main(String[] args) {
 17:         System.out.println("\n\n"
 18:                 + "Linear Search\n"
 19:                 + "=============\n");

 21:         setTraceLevel();

 23:         // create an array of random integers
 24:         int[] numbers = Common.randomNumbers(HOW_MANY, MAX / 10, MAX);
 25:         Common.printArray(numbers);
 26:         Common.pause();

 28:         // sort it
 29:         int value = Common.randomNumber(MAX / 10, MAX);
 30:         System.out.println("Searching for " + value + ":");
 31:         int posn = linearSearch(numbers, value);

 33:         // show result
 34:         if (posn >= 0) {
 35:             System.out.println(value + " found at " + posn + ":");
 36:             Common.printArray(numbers, posn, posn + 1);
 37:         } else {
 38:             System.out.println(value + " not found");
 39:         }
 40:         Common.pause();
 41:     }

 43:     /**
 44:      * Prompt for and read a level of tracing to do.
 45:      */
 46:     public static void setTraceLevel() {
 47:         String traceMenu = "Enter a trace level: \n"
 48:                 + "  0 - no tracing\n"
 49:                 + "  1 - tracing\n\n"
 50:                 + "Trace level: ";

 52:         System.out.print(traceMenu);
 53:         traceLevel = KBD.nextInt();
 54:         KBD.nextLine();
 55:         while (traceLevel < 0 || 1 < traceLevel) {
 56:             System.out.print(traceMenu);
 57:             traceLevel = KBD.nextInt();
 58:             KBD.nextLine();
 59:         }
 60:     }

 62:     /**
 63:      * Search the given array.
 64:      *
 65:      * @param arr the array to search
 66:      * @param value the value to search for
 67:      */
 68:     public static int linearSearch(int[] arr, int value) {
 69:         for (int i = 0; i < arr.length; ++i) {
 70:             if (traceLevel > 0) {
 71:                 System.out.println("Searching for " + value + "...");
 72:                 Common.printArray(arr, i, i + 1);
 73:                 Common.pause();
 74:             }
 75:             if (arr[i] == value) {
 76:                 return i;
 77:             }
 78:         }
 79:         return -1;
 80:     }
 81: }