Source of LinearSearchDemo.java


  1: //LinearSearchDemo.java

  3: import java.util.Scanner;

  5: public class LinearSearchDemo
  6: {
  7:     private static int linearSearch(int[] numbers, int key)
  8:     {
  9:         for (int i = 0; i < numbers.length; i++)
 10:         {
 11:             if (numbers[i] == key)
 12:             {
 13:                 return i;
 14:             }
 15:         }
 16:         return -1; // not found
 17:     }

 19:     // Main program to test the linearSearch() method
 20:     public static void main(String[] args)
 21:     {
 22:         int[] numbers = { 2, 4, 7, 10, 11, 32, 45, 87 };
 23:         System.out.print("NUMBERS: ");
 24:         for (int i = 0; i < numbers.length; i++)
 25:         {
 26:             System.out.print(numbers[i] + " ");
 27:         }
 28:         System.out.println();

 30:         Scanner scnr = new Scanner(System.in);
 31:         System.out.print("Enter an integer value: ");
 32:         int key = scnr.nextInt();
 33:         int keyIndex = linearSearch(numbers, key);

 35:         if (keyIndex == -1)
 36:         {
 37:             System.out.println(key + " was not found.");
 38:         }
 39:         else
 40:         {
 41:             System.out.printf("Found %d at index %d.\n", key, keyIndex);
 42:         }
 43:     }
 44: }