LinearSearchDemo.java.html

  1  import java.util.Arrays;
  2  import java.util.Scanner;
  3  
  4  /**
  5     This program demonstrates the linear search algorithm.
  6  */
  7  public class LinearSearchDemo
  8  {  
  9     public static void main(String[] args)
 10     {  
 11        int[] a = ArrayUtil.randomIntArray(20, 100);
 12        System.out.println(Arrays.toString(a));
 13        Scanner in = new Scanner(System.in);
 14  
 15        boolean done = false;
 16        while (!done)
 17        {
 18           System.out.print("Enter number to search for, -1 to quit: ");
 19           int n = in.nextInt();
 20           if (n == -1) 
 21           {
 22              done = true;
 23           }
 24           else
 25           {
 26              int pos = LinearSearcher.search(a, n);
 27              System.out.println("Found in position " + pos);
 28           }
 29        }
 30     }
 31  }