在这里,我们将解释如何编写一个 Java 程序来执行线性搜索。
线性搜索也称为顺序搜索。它是一种简单的搜索方法。与其他搜索方法相比,它的性能非常慢。在线性搜索中,搜索是在整个列表中执行的。它按顺序检查列表中的所有元素。它将列表中的每个元素与搜索元素进行比较,直到找到该元素或到达列表末尾。
首先,我们必须声明类 LinearSearch。声明整数变量 i、limit、key。创建扫描器类对象 sc。读取数组元素的限制作为 limit。声明一个大小为 limit 的整数数组。使用 for 循环将数组元素读入 array[i]。将搜索元素读入 key。然后使用 for 循环通过 if 条件检查数组的每个元素是否等于 key 元素。如果 array[i]==key,则显示在位置 i+1 找到该元素并中断循环。否则,将 i 增加 1 并继续该过程,直到检查所有元素。如果 i 达到 limit,则显示未找到该元素。
步骤 1:声明具有 public 修饰符的类 LinearSearch。
步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始
步骤 3:声明整数变量 i、limit、key。
步骤 4:将数组的限制读入变量 limit。
步骤 5:声明一个大小为 limit 的数组。
步骤 6:使用 for 循环 将元素读入数组。
步骤 7:将要搜索的元素读入变量 key。
步骤 8:使用 for 循环,条件为 i
步骤 9:检查 array[i]==key,如果为真,则显示在位置 i+1 找到该元素并转到步骤 11。
步骤 10:将 i 增加 1 并重复步骤 9。
步骤 11:检查 i=limit,然后显示未找到该元素。
import java.util.Scanner;
public class LinearSearch
{
public static void main(String args[])
{
int i, limit, key;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit of numbers:");
limit = sc.nextInt();
int array[] = new int[limit];
System.out.println("Enter " +limit + " numbers:");
for (i = 0; i < limit; i++)
array[i] = sc.nextInt();
System.out.println("Enter the search element:");
key = sc.nextInt();
for (i = 0; i < limit; i++)
{
if (array[i] == key)
{
System.out.println("The search element "+ key +" is found at location "+ (i+1));
break;
}
}
if (i == limit)
System.out.println("The search element "+ key +" is not found");
}
}
Enter the limit of numbers:5 Enter 5 numbers: 2 6 88 10 120 Enter the search element:88 The search element 88 is found at location 3