线性搜索: Python, C++ 例如:

⚡ 智能摘要

线性搜索按顺序检查列表中的每个元素,直到找到目标值或列表结束。此方法不需要数据排序,时间复杂度为 O(n),并且非常适合处理小型或无序集合。

  • 🔍 核心机制: 线性搜索将目标与索引从零开始的每个元素进行比较,直到找到匹配项并返回其位置,或者扫描结束并返回 -1。
  • ⚙️ 功能行为: 当值存在时,该例程返回 0 到 n-1 之间的索引;当搜索元素在数组中不存在时,则返回 -1。
  • 💻 Code 实施方案: 工进 C++ 和 Python 例如,使用单个循环遍历整数数组,并打印搜索值出现的索引。
  • 📊 复杂性概况: 时间复杂度在最坏和平均情况下达到 O(n),最好情况下达到 O(1),而空间复杂度总体上保持 O(n)。
  • 🚀 优化技术: 转置和移至前面会将经常搜索的键重新排序到前面,从而减少重复搜索中的比较次数。

线性搜索算法

什么是搜索算法?

A searching algorithm is designed to find an element or object from a collection of elements or objects with a given data structure. For example, search the minimum height from a given list of heights, or search for the highest mark from a list or array of numbers. Few popular searching algorithms include "Linear Search", "Binary Search", "Jump Search", "Fibonacci Search," etc.

什么是线性搜索?

线性搜寻 线性搜索是最简单的搜索算法之一。它从给定的列表或数组中逐个查找指定的元素。线性搜索遍历整个列表,检查是否存在与搜索元素相等的特定元素。它也被称为…… 顺序搜索.

线性搜索函数有什么作用?

An array of integers is given as "Numbers," and a variable "item" contains the integer number to search.

现在,线性搜索算法可以提供以下输出:

  • "-1"; this means that the given element is not found in the array.
  • Any number between 0 to n-1; means that the search element is found, and it returns the index of the element on the array. Here, "n" represents the size of the array.

线性搜索如何工作?

假设我们有一个包含整数的数组。任务是在数组中找到给定的数字。

  • 如果数字位于数组中,我们需要返回该数字的索引。
  • 如果未找到给定的数字,则它将返回 -1。

In the flowchart, "Data" is the integer array, "N" is the size of the array, and the "item" is the number we want to search in the array.

线性搜索算法流程图:

线性搜索算法流程图

流程图的步骤如下:

步骤1) Read the search item, "item."

步骤2) 初始化 i=0 和 index=-1。

步骤3) 如果我

步骤4) If Data[i] equals to "item," then go to step 5. Else go to step 6.

步骤5) 索引 = i(因为该项目位于索引 i 处)。转到步骤 8。

步骤6) i=i+1。

步骤7) 转到步骤3。

步骤8) 停止。

为简单起见,我们以整数数组为例。线性搜索也适用于字符串、对象数组或结构体。

昵称 Code 顺序搜索算法

以下伪代码描述了上述线性搜索的逻辑。它从数组的第一个索引开始遍历,如果找到匹配项则返回其位置,否则返回 -1。

function linearSearch: in → Data[], item
    foundAt = -1
    for i in (0 to data.length):
        if data[i] equals item:
            // item is found in the array
            // returning the index
            return i
    // item not found in the array
    // -1 means no item found, as a negative index is not valid
    return -1

C++ Code 线性搜索示例

以下是完整的 C++ 实现顺序搜索并打印搜索值的索引的程序。

#include <bits/stdc++.h>
using namespace std;

int linearSearch(int *arr, int item, int n) {
    int idx = -1;
    for (int i = 0; i < n; i++) {
        if (arr[i] == item) {
            idx = i;
            break;
        }
    }
    return idx;
}

int main() {
    int array[] = {1, 9, 8, 7, 6, 3, 11, 4, 6, 9, 7, 2, 0, 19, -10};
    int n = sizeof(array) / sizeof(array[0]);
    int item;
    cout << "Enter a number to search: ";
    cin >> item;
    int idx = linearSearch(array, item, n);
    if (idx >= 0) {
        cout << item << " is found at index " << idx << endl;
    } else {
        cout << "Could not find " << item << " in the array" << endl;
    }
}

输出:

Enter a number to search: -10
-10 is found at index 14

Python Code 线性搜索示例

同样的逻辑 Python 使用单个循环遍历列表索引,并返回匹配元素的位置。

def linearSearch(data, item):
    for i in range(len(data)):
        if data[i] == item:
            return i
    return -1

data = [1, 9, 8, 7, 6, 3, 11, 4, 6, 9, 7, 2, 0, 19, -10]
item = int(input("Enter a number to search: "))
idx = linearSearch(data, item)
if idx >= 0:
    print("{} is found at index {}".format(item, idx))
else:
    print("{} was not found".format(item))

输出:

Enter a number to search: -10
-10 is found at index 14

线性搜索算法的复杂度分析

通常,时间复杂度指的是完成特定任务所需的CPU时间。在线性搜索算法中,任务是从数组元素中找到搜索键。

三种类型的时间复杂度为:

  • 最坏的情况下
  • 最佳案例情景
  • 平均情况

最坏情况下线性搜索的时间复杂度:

Let us say we need to perform a linear search in an array with a size of "n". We can find the search item between index 0 to n-1. In the worst-case scenario, the algorithm will try to match all the elements from the array with the search element.

In that case, the worst-case complexity will be O(n). Here, "O" — big O Notation — means the complexity function.

最佳情况下线性搜索的时间复杂度:

假设我们要查找数组中位于第一个位置的元素。在这种情况下,线性搜索算法不会搜索数组中的所有 n 个元素。因此,其复杂度为 O(1),即常数时间。

平均情况下线性搜索的时间复杂度:

当在数组的中间索引处找到一个元素时,可以说线性搜索的平均情况复杂度为 O(N),其中 N 表示数组的长度。

线性搜索算法的空间复杂度:

线性搜索的空间复杂度始终为 O(N),因为线性搜索函数中不需要存储或使用任何类型的临时变量。

如何改进线性搜索算法

Search can be done multiple times throughout the program's lifecycle. It is also possible that we are running the linear search algorithm and searching for any specific key several times. We can use the "二分查找算法" if the array is a sorted array.

假设数组由 10 万个数字组成,并且目标元素位于第 5000 个索引处。因此,算法将尝试比较 5000 个元素。现在,比较是 CPU 密集型任务。为了优化线性搜索算法,我们有两个选择。

  • 换位
  • 移到前面

换位:

在这种方法中,我们将搜索元素与其在数组中的前一个元素交换位置。例如,假设你有一个如下所示的数组:

数据[] = {1,5,9,8,7,3,4,11}

现在,我们要搜索4.转置的步骤:

线性搜索中的转置

步骤1) "4" is found at index 6. It took six comparisons.

步骤2) 交换 data[6] 和 data[5]。然后数据数组将如下所示:

数据[] = {1,5,9,8,7,4,3,11}

步骤3) 再次搜索 4。在索引 5 处找到。这次进行了五次比较。

步骤4) 交换 data[5] 和 data[4]。然后 data 数组将如下所示:

数据[] = {1,5,9,8,4,7,3,11}

现在,如果你仔细观察,就会发现,某个键被搜索的频率越高,其索引就越小,从而减少了比较次数。

移至最前:

在这种方法中,我们将搜索元素交换到索引 0。因为如果再次搜索该元素,我们可以在 O(1) 时间内找到它。

在线性搜索中移至最前

线性搜索算法的应用

以下是我们可以使用的一些线性搜索应用程序。

  • 对于小型数组或列表中只有少量元素的情况,使用线性搜索更容易。
  • 线性搜索方法可以用于单个或 多维数组 或其他数据结构。
  • Generally, linear search is simple and efficient to perform a search in the "unordered" data. We can fetch a single data from the given unordered list easily.

常见问题

线性搜索在数据预处理期间扫描无序特征列表、小型查找表和标签集。当数据未排序或规模太小而无法构建索引时,人工智能流程通常使用线性搜索来查找值。

是的。人工智能助手可以编写线性搜索程序。 Python, C++ 或 Java 仅凭简单的描述即可得出结论。逻辑很简单,所以出错的概率很低,但您仍然应该测试一些极端情况,例如空数组或缺少元素。

线性搜索按顺序检查每个元素,并且在 O(n) 时间内可以处理无序数据。 二进制搜索 以 O(log n) 的时间复杂度反复将已排序数组减半,因此对于大型已排序集合来说速度要快得多。

当数据量小、无序或频繁变化时,应使用线性搜索,因为先排序会比直接扫描成本更高。线性搜索也适用于链表和无法进行随机访问的单次扫描搜索。

总结一下这篇文章: