Java 实例 线性搜索

来源:这里教程网 时间:2026-02-17 20:17:13 作者:

该程序使用线性搜索算法,在用户输入的所有其他数字中找出数字。

/* Program: Linear Search Example * Written by: Chaitanya from beginnersbook.com * Input: Number of elements, element's values, value to be searched * 输出:Position of the number input by user among other numbers*/import java.util.Scanner;class LinearSearchExample{   public static void main(String args[])   {      int counter, num, item, array[];      //To capture user input      Scanner input = new Scanner(System.in);      System.out.println("Enter number of elements:");      num = input.nextInt();       //Creating array to store the all the numbers      array = new int[num];       System.out.println("Enter " + num + " integers");      //Loop to store each numbers in array      for (counter = 0; counter < num; counter++)        array[counter] = input.nextInt();      System.out.println("Enter the search value:");      item = input.nextInt();      for (counter = 0; counter < num; counter++)      {         if (array[counter] == item)          {           System.out.println(item+" is present at location "+(counter+1));           /*Item is found so to stop the search and to come out of the             * loop use break statement.*/           break;         }      }      if (counter == num)        System.out.println(item + " doesn't exist in array.");   }}

输出 1:

Enter number of elements:6Enter 6 integers2233451399Enter the search value:4545 is present at location 3

输出 2:

Enter number of elements:4Enter 4 integers112245Enter the search value:9999 doesn't exist in array.

相关推荐