package chapter5;

/**
 * Title:        Chapter 5, "Arrays"
 * Description:  Examples for Chapter 2
 * Copyright:    Copyright (c) 2000
 * Company:      Armstrong Atlantic State University
 * @author Y. Daniel Liang
 * @version 1.0
 */

// LinearSearch.java: Search for a number in a list

import chapter2.MyInput;

public class LinearSearch
{
  /**Main method*/
  public static void main(String[] args)
  {
    int[] list = new int[10];

    // Create the list randomly and display it
    System.out.print("The list is  ");
    for (int i=0; i<list.length; i++)
    {
      list[i] = (int)(Math.random()*100);
      System.out.print(list[i]+"  ");
    }
    System.out.println();

    // Prompt the user to enter a key
    System.out.print("Enter a key  ");
    int key = MyInput.readInt();
    int index = linearSearch(key, list);
    if (index != -1)
      System.out.println("The key is found in index "+index);
    else
      System.out.println("The key is not found in the list");
  }

  /**The method for finding a key in the list*/
  public static int linearSearch(int key, int[] list)
  {
    for (int i=0; i<list.length; i++)
      if (key == list[i])
        return i;
    return -1;
  }
}