JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

Linear Search

Author:JIYIK Last Updated:2025/03/19 Views:

Linear search is the simplest search algorithm. It is also called sequential search because in this algorithm, we look for the matching element by going through the entire array and comparing each element with the required item. If the required element is found, then the index or the element is returned; otherwise, we continue searching until we exhaust the array. We can also look for multiple occurrences of an item in an array. It is mainly used to search for an item in an unsorted array. Since it is much slower than binary search, it is not used in practice.

Linear Search Algorithm

Suppose we have an unsorted array A[]containing nelements and we want to find an element - X.

  • Use a for loop to iterate over all the elements in an array starting from the leftmost element and do the following.
    • If the value of A[i] matches X, return index i. (If there could be more than one element matching X, instead of returning index i, print all the indices or store all the indices in an array and return that array.)
    • Otherwise continue with the next element.
    • If you are at the last element of the array, exit the for loop.
  • If none of the elements match, -1 is returned.

Linear Search Example

Suppose we have the array: (5, 3, 4, 2, 1, 6).

  • Case 1: We are looking for X= 5.

The first element itself is a match and we return the index 0. (Best case)

  • Case 2: We want to find X= 1.

We iterate over the array and reach the index 4, find a matching index and return that index. (Average case)

  • Case 3: We are looking for X= 9.

We iterate over the array, but when we reach the last element of the array, no matching element is found. We return -1. (worst case)

Implementation of Linear Search Algorithm

Linear search algorithm for a single match

#include <iostream>
using namespace std;

int search(int arr[], int n, int x) {
    // Traverse the array sequentially
    for (int i = 0; i < n; i++) {
        if (arr[i] == x)
            return i;
    }
    return -1;
}

int main() {
    int n = 5;
    int arr[] = {2, 4, 0, 1, 9};
    int x = 1;
    int result = search(arr, n, x);
    if (result == -1) cout << "Element not found";
    else cout << "Element found at index: " << result;
}

Linear search algorithm for multiple matches

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

vector<int> search(int arr[], int n, int x) {
    vector<int>ans;
    // Traverse the array sequentially
    for (int i = 0; i < n; i++) {
        if (arr[i] == x) {
            ans.push_back(i);
        }
    }
    return ans;
}

int main() {
    int n = 9;
    int arr[] = {2, 4, 0, 1, 9, 2, 1, 2, 1};
    int x = 1;
    vector<int> res = search(arr, n, x);
    if (res.empty()) {
        cout << "Element not found!!";
    }
    else {
        cout << "Element found at ";
        for (int i = 0; i < res.size(); i++) {
            cout << res[i] << " ";
        }
    }
}

Complexity of Linear Search Algorithm

Time Complexity

  • Average situation

The time complexity of the linear search algorithm is O(n).

  • Best Case

The best case time complexity is O(1). This occurs when the element being searched is the first element in the array.

  • Worst case scenario

The worst case is when the element we are searching for is not in the array or is at the last index of the array. The worst case time complexity is O(n).

Space complexity

The space complexity of this algorithm depends on the number of matches and the implementation used. In general, the space complexity is O(1), but it can be higher if you store multiple match indices in an array.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Learning the Sorting Algorithm - Insertion Sort (Concepts)

Publish Date:2025/03/19 Views:95 Category:ALGORITHM

What is "insertion sort"? The concept is as follows: each time a record to be sorted is inserted into the previously sorted sequence according to its key size, until all records are inserted. Concepts are always somewhat abstract, and can a

Learning path of sorting algorithm - direct insertion sort

Publish Date:2025/03/19 Views:175 Category:ALGORITHM

This article follows up on Insertion Sort (Concepts) and presents the implementation steps and code for direct insertion sort. Since the Concepts section already has a large number of illustrations, it would be a bit long-winded to provide

Learning the sorting algorithm - Binary Insertion Sort

Publish Date:2025/03/19 Views:142 Category:ALGORITHM

This article follows the insertion sort (concept article) and presents the implementation steps and implementation code of the binary insertion sort Binary Insertion Sort Algorithm Steps Treat the first element of the first sequence to be s

The road to learning sorting algorithms - table insertion sort

Publish Date:2025/03/19 Views:193 Category:ALGORITHM

Table insertion sort was briefly mentioned in Insertion sort (concept) . I briefly summarized it and wrote this article. You can refer to it if you need it. Table insertion sort, as the name implies, uses an index table to sort the original

The road to learning sorting algorithms - Hill sort

Publish Date:2025/03/19 Views:50 Category:ALGORITHM

Hill sort is named after the designer of the algorithm, Hill. It is an improvement of Hill on the basis of insertion sort and can be said to be a special insertion sort. Here are the properties of insertion sort: First of all, the insertion

Things about the singleton design pattern

Publish Date:2025/03/19 Views:51 Category:ALGORITHM

The singleton design pattern is one of the most commonly used design patterns. The singleton design pattern, just by its name, you can roughly know its meaning. Single means one; instance means instance object. So a singleton has only one i

The road to learning sorting algorithms - merge sort

Publish Date:2025/03/19 Views:157 Category:ALGORITHM

Let's first look at the definition of merge sort Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of the Divide and Conquer method. Merge the ordered subsequences to obt

The road to learning sorting algorithms - quick sort

Publish Date:2025/03/19 Views:121 Category:ALGORITHM

Quick sort is a sorting algorithm developed by Tony Hall. On average, sorting n items requires O(n log n) comparisons. In the worst case, O(n2) comparisons are required, but this is uncommon. In fact, quick sort is often significantly faste

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial