(Translated by https://www.hiragana.jp/)
Linear Search Algorithm - GeeksforGeeks
Open In App

Linear Search Algorithm

Last Updated : 28 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array, arr of n integers, and an integer element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesn’t exist.

Input: arr[] = [1, 2, 3, 4], x = 3
Output: 2
Explanation: There is one test case with array as [1, 2, 3 4] and element to be searched as 3. Since 3 is present at index 2, the output is 2.

Input: arr[] = [10, 8, 30, 4, 5], x = 5
Output: 4
Explanation: For array [1, 2, 3, 4, 5], the element to be searched is 5 and it is at index 4. So, the output is 4.

Input: arr[] = [10, 8, 30], x = 6
Output: -1
Explanation: The element to be searched is 6 and its not present, so we return -1.

In Linear Search, we iterate over all the elements of the array and check if it the current element is equal to the target element. If we find any element to be equal to the target element, then return the index of the current element. Otherwise, if no element is equal to the target element, then return -1 as the element is not found. Linear search is also known as sequential search.

For example: Consider the array arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 30


Below is the implementation of the linear search algorithm:

C++
#include <iostream>
#include <vector>
using namespace std;

int search(vector<int>& arr, int x) {
    for (int i = 0; i < arr.size(); i++)
        if (arr[i] == x)
            return i;
    return -1;
}

int main() {
    vector<int> arr = {2, 3, 4, 10, 40};
    int x = 10;
    int res = search(arr, x);
    if (res == -1)
       cout << "Not Present";
    else
       cout << "Present at Index " << res;
    return 0;
}
C
// C code to linearly search x in arr[].

#include <stdio.h>

int search(int arr[], int N, int x)
{
    for (int i = 0; i < N; i++)
        if (arr[i] == x)
            return i;
    return -1;
}

// Driver code
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int x = 10;
    int N = sizeof(arr) / sizeof(arr[0]);

    // Function call
    int result = search(arr, N, x);
    (result == -1)
        ? printf("Element is not present in array")
        : printf("Element is present at index %d", result);
    return 0;
}
Java
// Java code for linearly searching x in arr[]. 

import java.io.*;

class GFG {
    public static int search(int arr[], int N, int x)
    {
        for (int i = 0; i < N; i++) {
            if (arr[i] == x)
                return i;
        }
        return -1;
    }

    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 2, 3, 4, 10, 40 };
        int x = 10;

        // Function call
        int result = search(arr, arr.length, x);
        if (result == -1)
            System.out.print(
                "Element is not present in array");
        else
            System.out.print("Element is present at index "
                             + result);
    }
}
Python
# Python3 code to linearly search x in arr[].


def search(arr, N, x):

    for i in range(0, N):
        if (arr[i] == x):
            return i
    return -1


# Driver Code
if __name__ == "__main__":
    arr = [2, 3, 4, 10, 40]
    x = 10
    N = len(arr)

    # Function call
    result = search(arr, N, x)
    if(result == -1):
        print("Element is not present in array")
    else:
        print("Element is present at index", result)
C#
// C# code to linearly search x in arr[].

using System;

class GFG {
    public static int search(int[] arr, int N, int x)
    {
        for (int i = 0; i < N; i++) {
            if (arr[i] == x)
                return i;
        }
        return -1;
    }

    // Driver's code
    public static void Main()
    {
        int[] arr = { 2, 3, 4, 10, 40 };
        int x = 10;

        // Function call
        int result = search(arr, arr.Length, x);
        if (result == -1)
            Console.WriteLine(
                "Element is not present in array");
        else
            Console.WriteLine("Element is present at index "
                              + result);
    }
}

// This code is contributed by DrRoot_
JavaScript
// Javascript code to linearly search x in arr[].

function search(arr, n, x)
{
    for (let i = 0; i < n; i++)
        if (arr[i] == x)
            return i;
    return -1;
}

// Driver code

    let arr = [ 2, 3, 4, 10, 40 ];
    let x = 10;
    let n = arr.length;

    // Function call
    let result = search(arr, n, x);
    (result == -1)
        ? console.log("Element is not present in array")
        : console.log("Element is present at index " + result);

// This code is contributed by Manoj
PHP
<?php
// PHP code for linearly search x in arr[].

function search($arr, $n, $x)
{
    for($i = 0; $i < $n; $i++) {
        if($arr[$i] == $x)
            return $i;
    }
    return -1;
}

// Driver Code
$arr = array(2, 3, 4, 10, 40); 
$x = 10;

// Function call
$result = search($arr, sizeof($arr), $x);
if($result == -1)
    echo "Element is not present in array";
else
    echo "Element is present at index " ,
                                 $result;

// This code is contributed
// by jit_t
?>

Output
Present at Index 3

Time Complexity:

  • Best Case: In the best case, the key might be present at the first index. So the best case complexity is O(1)
  • Worst Case: In the worst case, the key might be present at the last index i.e., opposite to the end from which the search has started in the list. So the worst-case complexity is O(N) where N is the size of the list.
  • Average Case: O(N)

Auxiliary Space: O(1) as except for the variable to iterate through the list, no other variable is used. 

  • Unsorted Lists: When we have an unsorted array or list, linear search is most commonly used to find any element in the collection.
  • Small Data Sets: Linear Search is preferred over binary search when we have small data sets with
  • Searching Linked Lists: In linked list implementations, linear search is commonly used to find elements within the list. Each node is checked sequentially until the desired element is found.
  • Simple Implementation: Linear Search is much easier to understand and implement as compared to Binary Search or Ternary Search.
  • Linear search can be used irrespective of whether the array is sorted or not. It can be used on arrays of any data type.
  • Does not require any additional memory.
  • It is a well-suited algorithm for small datasets.
  • Linear search has a time complexity of O(N), which in turn makes it slow for large datasets.
  • Not suitable for large arrays.
  • When we are dealing with a small dataset.
  • When you are searching for a dataset stored in contiguous memory.

1. What is linear search algorithm?

Linear search algorithm, also known as sequential search algorithm, is a simple searching algorithm that traverses a list or array sequentially to find a target element. In Linear Search, we can get the

2. How does linear search algorithm work?

Linear search algorithm iterates through each element in the list or array, comparing it with the target element until a match is found or the end of the list is reached. If the end of the list is reached, then it means that the target element is not present in the array.

3. What is the time complexity of linear search algorithm?

The time complexity of linear search algorithm is O(n), where n is the number of elements in the list or array being searched. This means the time taken for searching increases linearly with the size of the input.

4. When is linear search algorithm preferred over other searching algorithms?

Linear search algorithm is preferred when the list or array is unsorted, or when the size of the input is relatively small. It’s simple to implement and doesn’t require the data to be in any specific order.

5. What are the advantages of linear search algorithm?

Linear search algorithm is easy to implement, and it works efficiently on small-sized arrays or lists. It doesn’t require any pre-processing like sorting, making it suitable for dynamic data structures.

6. What are the disadvantages of linear search algorithm?

Linear search algorithm becomes inefficient for large-sized arrays or lists, as it needs to scan through each element sequentially. It has a time complexity of O(n), which means the search time grows linearly with the size of the input.

7. How do you implement linear search algorithm in programming languages like Python, Java, or C++?

Linear search algorithm can be implemented using loops to iterate through the elements of the array or list, comparing each element with the target value until a match is found or the end of the list is reached.

8. Can linear search algorithm be applied to other data structures?

Yes, linear search algorithm can be applied not only to arrays or lists but also to other linear data structures like linked lists. The principle remains the same: iterating through each element until the target is found or the end is reached.

9. Is linear search algorithm suitable for sorted arrays or lists?

While linear search algorithm can still be used on sorted arrays or lists, it’s not the most efficient option. Binary search, for example, is more suitable for sorted data as it has a time complexity of O(log n).

10. What are some real-world applications of linear search algorithm?

Linear search algorithm can be used in scenarios such as searching for a specific value in a phone book, searching for a name in an unsorted list of contacts, or finding an item in a grocery list. It’s often used in scenarios where the data size is small or not expected to grow significantly.

Related Articles:



Previous Article
Next Article

Similar Reads

Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Difference Between Linear Search and Jump Search
Linear Search and Jump Search are two different techniques used to find an element in a list. Each algorithm has its own set of characteristics, advantages, and limitations, making them suitable for different scenarios. This article explores the key differences between Linear Search and Jump Search. What is Linear Search?Linear Search, also known a
3 min read
Time and Space Complexity of Linear Search Algorithm
The time complexity of the Linear Search algorithm is O(n), where n is the number of elements in the array. The space complexity is O(1) as it requires a constant amount of extra space regardless of the input size. AspectComplexityTime ComplexityO(n)Space ComplexityO(1)Let's explore the detailed time and space complexity of the Linear Search Algori
2 min read
Two Way Linear Search Algorithm
Two-Way Linear Search Algorithm is based on the principle of Linear Search, but the search is conducted from both ends towards the center of the array. In this article, we will learn about the basics of Two Way Linear Search Algorithm, its advantages, implementation etc. What is Two-Way Linear Search?Two Way Linear Search is a searching technique w
6 min read
Recursive Linear Search Algorithm
Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set. How Linear Search Works?Linear search works by comparing each element of the data structure with the key to be found. To learn the w
6 min read
Z algorithm (Linear time pattern searching Algorithm)
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is "n" and the length of the pattern is "m," then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of this algorithm is the same as the KMP algorithm, but
13 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Difference between Linear and Non-linear Data Structures
Linear Data Structure: Data structure where data elements are arranged sequentially or linearly where each and every element is attached to its previous and next adjacent is called a linear data structure. In linear data structure, single level is involved. Therefore, we can traverse all the elements in single run only. Linear data structures are e
5 min read
Linear search using Multi-threading
Given a large file of integers, search for a particular element in it using multi-threading. Examples: Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 20Key element foundInput :1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 202Key not presentPrerequisite : Multi-threading Recommen
6 min read
Number of comparisons in each direction for m queries in linear search
Given an array containing N distinct elements. There are M queries, each containing an integer X and asking for the index of X in the array. For each query, the task is to perform linear search X from left to right and count the number of comparisons it took to find X and do the same thing right to left. In the end, print the total number of compar
7 min read
What is Linear Search?
Linear search is defined as the searching algorithm where the list or data set is traversed from one end to find the desired value. Linear search works by sequentially checking each element in the list until the desired value is found or the end of the list is reached. Properties of Linear search :Time Complexity: The worst case time complexity of
3 min read
What is linear search useful for?
Linear search is a fundamental search algorithm that iterates through a list of elements one by one, comparing each element to the target value. If the target value is found, the search stops and returns the index of the element. Otherwise, the search continues until the end of the list is reached, at which point it returns -1 to indicate that the
3 min read
Where is linear search used in real life?
Linear search is a fundamental searching algorithm that iterates through a list of elements one by one until the desired element is found. While it is not the most efficient searching algorithm for large datasets, linear search has several practical applications in real-life scenarios. 1. Finding Contact InformationLinear search can be found in app
2 min read
Does Linear Search require the list to be sorted?
Linear search is a simple search algorithm that iterates through a list of elements one by one until it finds the target element. It is often used when the list is small or unsorted. No, linear search does not require the list to be sorted. This is because linear search simply compares the target element to each element in the list, regardless of t
2 min read
Linear Search Visualization using JavaScript
GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Linear Search using JavaScript. We will see how the elements are being traversed in Linear Search until the given element is found. We will also visualize the time complexity of Linear Search. Reference: Linear SearchAsynchronous Functio
3 min read
Sentinel Linear Search
Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. In a traditional linear search, only N comparisons are made, and in a Sentinel Linear Search, the sentinel value is used to avoid any out-of-bounds comparisons, but there is no additional comp
7 min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
In Manacher's Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. Here we will implement the same.We have seen that there are no new character comparison needed in case 1 and case 2. In case 3 and case 4, necessary new comparison are needed. In followi
15+ min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
Given a string, find the longest substring which is palindrome. if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”if the given string is “abaaba”, the output should be “abaaba”if the given string is “abababa”, the output should be “abababa”if the given string is “abcbabcbabcba”, the output should be “abcbabcbabcba” We have
5 min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 2
In Manacher's Algorithm - Part 1, we gone through some of the basics and LPS length array. Here we will see how to calculate LPS length array efficiently. To calculate LPS array efficiently, we need to understand how LPS length for any position may relate to LPS length value of any previous already calculated position. For string “abaaba”, we see f
11 min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
In Manacher's Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. In Part 3, we implemented the same. Here we will review the four cases again and try to see it differently and implement the same. All four cases depends on LPS length value at currentLe
12 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Difference between Best-First Search and A* Search?
Best-First Search: Best-First search is a searching algorithm used to find the shortest path which uses distance as a heuristic. The distance between the starting node and the goal node is taken as heuristics. It defines the evaluation function for each node n in the graph as f(n) = h(n) where h(n) is heuristics function. A*Search: A*search is a se
2 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include <bits/stdc++.h> using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
Sublist Search (Search a linked list in another list)
Given two linked lists, the task is to check whether the first list is present in 2nd list or not. Examples: Input: list1 = 10->20 list2 = 5->10->20 Output : LIST FOUNDInput: list1 = 1->2->3->4 list2 = 1->2->1->2->3->4 Output: LIST FOUNDInput: list1 = 1->2->3->4 list2 = 1->2->2->1->2->3 Outpu
15+ min read
Practice Tags :
three90RightbarBannerImg