线性搜索是一种顺序搜索算法,我们从一端开始检查列表中的每个元素,直到找到所需的元素。它是最简单的搜索算法。
线性搜索的图解
按照以下步骤k = 1在下面的列表中搜索元素。
![]() |
|---|
| 要搜索的数组 |
- 从第一个元素开始,比较 克 与每个元素 X.
|
|
| —- |
| 与每个元素进行比较 |
- 如果x == k,则返回索引。
|
|
| —- |
| 找到元素 |
- 否则,返回未找到.
线性搜索的伪码
LinearSearch(array, key)for each item in the arrayif item == valuereturn its index
线性搜索的实现
// Linear Search in Javaclass LinearSearch {public static int linearSearch(int array[], int x) {int n = array.length;// Going through array sequenciallyfor (int i = 0; i < n; i++) {if (array[i] == x)return i;}return -1;}public static void main(String args[]) {int array[] = { 2, 4, 0, 1, 9 };int x = 1;int result = linearSearch(array, x);if (result == -1)System.out.print("Element not found");elseSystem.out.print("Element found at index: " + result);}}
线性搜索复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(1)
线性搜索的应用
- 用于在较小数组(<100 项)中进行搜索操作。

