linearsearch.java

来自「此源码为机械工业出版社出版的《Java语言程序设计》第三版所配套的书中所有源代码」· Java 代码 · 共 37 行

JAVA
37
字号
// LinearSearch.java: Search for a number in a list
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;
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?