当前位置: 首页> 汽车> 行情 > 数据结构第23节 线性搜索

数据结构第23节 线性搜索

时间:2025/7/19 23:19:44来源:https://blog.csdn.net/hummhumm/article/details/140382673 浏览次数: 0次

线性搜索(Linear Search),也称为顺序搜索,是最基本的搜索算法之一。它的工作原理是通过遍历数组或列表中的每一个元素,直到找到目标值为止,或者遍历完所有元素后确定目标值不存在于列表中。

线性搜索的时间复杂度为O(n),其中n是列表中元素的数量。这是因为最坏情况下,你可能需要检查列表中的每一个元素才能找到目标值或确定它不在列表中。

Java实现线性搜索

下面是一个简单的Java代码示例,演示如何实现线性搜索:

public class LinearSearch {/*** Performs linear search on an array to find a target value.** @param array The array of integers to search through.* @param target The integer value to search for.* @return The index of the target if found, otherwise -1.*/public static int linearSearch(int[] array, int target) {for (int i = 0; i < array.length; i++) {if (array[i] == target) {return i; // Target found, return its index.}}return -1; // Target not found.}public static void main(String[] args) {int[] data = {5, 3, 9, 2, 8};int target = 9;int index = linearSearch(data, target);if (index != -1) {System.out.println("Element " + target + " found at index " + index);} else {System.out.println("Element " + target + " not found");}}
}

线性搜索过程解析

  1. 初始化:定义一个变量i作为索引,从0开始。

  2. 遍历数组:使用for循环遍历数组中的每一个元素,直到到达数组的末尾。

  3. 比较元素:在每一次循环中,将当前元素array[i]与目标值target进行比较。

  4. 找到目标值:如果array[i]等于target,则返回当前的索引i,表示目标值在数组中的位置。

  5. 未找到目标值:如果循环结束时仍未找到目标值,则返回-1,表示目标值不在数组中。

  6. 输出结果:根据返回的索引值判断目标值是否找到,并输出相应的信息。

注意事项

  • 线性搜索适用于未排序的数组或列表。
  • 如果数组很大,线性搜索可能效率较低,因为它需要遍历整个数组。
  • 对于经常进行搜索操作的场景,考虑使用更高效的搜索算法,如二分搜索或哈希表。

通过这个示例和解析,你可以更好地理解线性搜索算法的工作原理以及如何在Java中实现它。

如果你想要扩展线性搜索的代码,可以考虑添加一些额外的功能,比如处理可能的异常、增强输出信息、允许用户输入数据等。下面是一个扩展后的Java程序,它包含了这些功能:

import java.util.Scanner;public class ExtendedLinearSearch {/*** Performs linear search on an array to find a target value.** @param array The array of integers to search through.* @param target The integer value to search for.* @return The index of the target if found, otherwise -1.*/public static int linearSearch(int[] array, int target) {for (int i = 0; i < array.length; i++) {if (array[i] == target) {return i; // Target found, return its index.}}return -1; // Target not found.}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);// Ask user to enter the size of the arraySystem.out.print("Enter the number of elements in the array: ");int size = scanner.nextInt();// Create an array of given size and ask user to fill itint[] data = new int[size];System.out.println("Enter the elements of the array:");for (int i = 0; i < size; i++) {data[i] = scanner.nextInt();}// Ask user to enter the target valueSystem.out.print("Enter the target value to search: ");int target = scanner.nextInt();// Perform the searchint index = linearSearch(data, target);// Check if the target was found and print the resultif (index != -1) {System.out.println("Element " + target + " found at index " + index);} else {System.out.println("Element " + target + " not found");}scanner.close();}
}

在这个扩展版本中,程序会:

  1. 请求用户输入数组的大小和数组元素。
  2. 请求用户输入要搜索的目标值。
  3. 执行线性搜索。
  4. 根据搜索结果输出相应的信息。

此外,程序使用Scanner类从用户那里获取输入,确保了与用户的交互性。这使得程序更加灵活,可以在不同的输入下运行。当程序结束时,记得关闭Scanner对象以释放资源。

这样的代码扩展使得线性搜索算法更加实用和通用,可以应用于各种需要用户输入和动态数据处理的场景。

我们可以增加一些额外的功能,例如:

  1. 处理非法输入:确保用户输入有效的数字。
  2. 重复搜索功能:允许用户连续搜索多个目标,而不需要重启程序。
  3. 记录搜索次数和平均搜索时间:可以用于评估算法的性能。

下面是包含上述功能的Java代码:

import java.util.Scanner;public class AdvancedLinearSearch {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);long totalSearchTime = 0L;int totalSearches = 0;// Ask user to enter the size of the arraySystem.out.print("Enter the number of elements in the array: ");int size = getValidInteger(scanner);int[] data = new int[size];// Create an array of given size and ask user to fill itSystem.out.println("Enter the elements of the array:");for (int i = 0; i < size; i++) {data[i] = getValidInteger(scanner);}boolean continueSearching = true;while (continueSearching) {// Ask user to enter the target valueSystem.out.print("Enter the target value to search (or 'q' to quit): ");String input = scanner.next();if ("q".equals(input.toLowerCase())) {break;}int target = Integer.parseInt(input);// Record start time before searchlong startTime = System.currentTimeMillis();// Perform the searchint index = linearSearch(data, target);// Record end time after searchlong endTime = System.currentTimeMillis();long elapsedTime = endTime - startTime;totalSearchTime += elapsedTime;totalSearches++;// Check if the target was found and print the resultif (index != -1) {System.out.println("Element " + target + " found at index " + index);} else {System.out.println("Element " + target + " not found");}System.out.println("Time taken for search: " + elapsedTime + " ms\n");}// Print average search time if any searches were performedif (totalSearches > 0) {double averageSearchTime = (double) totalSearchTime / totalSearches;System.out.println("Average search time over " + totalSearches + " searches: " + averageSearchTime + " ms");}scanner.close();}private static int linearSearch(int[] array, int target) {for (int i = 0; i < array.length; i++) {if (array[i] == target) {return i; // Target found, return its index.}}return -1; // Target not found.}private static int getValidInteger(Scanner scanner) {while (!scanner.hasNextInt()) {System.out.print("Invalid input! Please enter a valid integer: ");scanner.next(); // discard invalid token}return scanner.nextInt();}
}

在这个版本中,我们增加了以下功能:

  • getValidInteger()方法用于确保从用户那里获取的输入是一个有效的整数,如果不是,会提示用户重新输入。
  • 在主循环中,我们提供了退出搜索的选项,用户可以通过输入字母’q’来结束搜索过程。
  • 计算每次搜索的执行时间,并在搜索完成后提供平均搜索时间的信息。

这些额外的功能使得程序更加健壮和用户友好,同时也便于性能分析。

关键字:数据结构第23节 线性搜索

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: