 Open in App
Not now

# Linear Search Algorithm

• Difficulty Level : Basic
• Last Updated : 30 Jan, 2023

### Linear search:-

 Linear search is the simplest method for searching.
 In Linear search technique of searching; the element to be found in searching the elements to
be found is searched sequentially in the list.
 This method can be performed on a sorted or an unsorted list (usually arrays).
 In case of a sorted list searching starts from 0th element and continues until the element is
found from the list or the element whose value is greater than (assuming the list is sorted in
ascending order), the value being searched is reached.
 As against this, searching in case of unsorted list also begins from the 0th element and
continues until the element or the end of the list is reached.
 The linear search algorithm searches all elements in the array sequentially.
 Its best execution time is 1, whereas the worst execution time is n, where n is the total
number of items in the search array.
 It is the most simple search algorithm in data structure and checks each item in the set of
elements until it matches the search element until the end of data collection.
 When data is unsorted, a linear search algorithm is preferred.

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. It is the easiest searching algorithm Linear Search Algorithm
Step 1: First, read the search element (Target element) in the array.
Step 2: In the second step compare the search element with the first element in the array.
Step 3: If both are matched, display “Target element is found” and terminate the Linear Search
function.
Step 4: If both are not matched, compare the search element with the next element in the array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target) element is compared with the
last element of the array.
Step 6 – If the last element in the list does not match, the Linear Search Function will be

Given an array arr[] of N elements, the task is to write a function to search a given element x in arr[].

Examples:

Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 110;
Output: 6
Explanation: Element x is present at index 6

Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 175;
Output: -1
Explanation: Element x is not present in arr[].

Follow the below idea to solve the problem:

Iterate from 0 to N-1 and compare the value of every index with x if they match return index

Follow the given steps to solve the problem:

1. Set the first element of the array as the current element.
2. If the current element is the target element, return its index.
3. If the current element is not the target element and if there are more elements in the array, set the current element to the next element and repeat step 2.
4. If the current element is not the target element and there are no more elements in the array, return -1 to indicate that the element was not found.

Below is the implementation of the above approach:

## C

 `// C code to linearly search x in arr[]. If x``// is present then return its location, otherwise``// return -1` `#include ` `int` `search(``int` `arr[], ``int` `N, ``int` `x)``{``    ``int` `i;``    ``for` `(i = 0; i < N; i++)``        ``if` `(arr[i] == x)``            ``return` `i;``    ``return` `-1;``}` `// Driver's code``int` `main(``void``)``{``    ``int` `arr[] = { 2, 3, 4, 10, 40 };``    ``int` `x = 10;``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);` `    ``// 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;``}`

## C++

 `// C++ code to linearly search x in arr[]. If x``// is present then return its location, otherwise``// return -1` `#include ``using` `namespace` `std;` `int` `search(``int` `arr[], ``int` `N, ``int` `x)``{``    ``int` `i;``    ``for` `(i = 0; i < N; i++)``        ``if` `(arr[i] == x)``            ``return` `i;``    ``return` `-1;``}` `// Driver's code``int` `main(``void``)``{``    ``int` `arr[] = { 2, 3, 4, 10, 40 };``    ``int` `x = 10;``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);` `    ``// Function call``    ``int` `result = search(arr, N, x);``    ``(result == -1)``        ``? cout << ``"Element is not present in array"``        ``: cout << ``"Element is present at index "` `<< result;``    ``return` `0;``}`

## Java

 `// Java code for linearly searching x in arr[]. If x``// is present then return its location, otherwise``// return -1` `class` `GFG {``    ``public` `static` `int` `search(``int` `arr[], ``int` `x)``    ``{``        ``int` `N = arr.length;``        ``for` `(``int` `i = ``0``; i < N; i++) {``            ``if` `(arr[i] == x)``                ``return` `i;``        ``}``        ``return` `-``1``;``    ``}` `    ``// Driver's code``    ``public` `static` `void` `main(String args[])``    ``{``        ``int` `arr[] = { ``2``, ``3``, ``4``, ``10``, ``40` `};``        ``int` `x = ``10``;` `        ``// Function call``        ``int` `result = search(arr, x);``        ``if` `(result == -``1``)``            ``System.out.print(``                ``"Element is not present in array"``);``        ``else``            ``System.out.print(``"Element is present at index "``                             ``+ result);``    ``}``}`

## Python3

 `# Python3 code to linearly search x in arr[].``# If x is present then return its location,``# otherwise return -1`  `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[]. If x``// is present then return its location, otherwise``// return -1``using` `System;` `class` `GFG {``    ``public` `static` `int` `search(``int``[] arr, ``int` `x)``    ``{``        ``int` `N = arr.Length;``        ``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, 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_`

## PHP

 ``

## Javascript

 ``

Output

`Element is present at index 3`

Time complexity: O(N)
Auxiliary Space: O(1)

Using STL:

The Approach:

Here we have a vector and we use find build function of vector library i.e vector iterator.

## C++

 `#include //Including the bits/stdc++ library for using vector and find functions``#include ``using` `namespace` `std;` `int` `main()``{``    ``vector<``int``> v{``        ``5, 15, 6, 9, 4``    ``}; ``// Declaring a vector v with initial values``    ``int` `key``        ``= 4; ``// Variable to store the element to be searched``    ``vector<``int``>::iterator it; ``// Declaring an iterator to``                              ``// iterate through the vector``    ``it = find(v.begin(), v.end(),``              ``key); ``// find function to search for the``                    ``// element in the vector``    ``if` `(it != v.end()) { ``// Checking if the element is``                         ``// present in the vector``        ``cout << key << ``" is Present in the vector"``             ``<< endl; ``// Printing if the element is present``                      ``// in the vector``    ``}``    ``else` `{``        ``cout << key << ``" is Not-Present in the vector"``             ``<< endl; ``// Printing if the element is not``                      ``// present in the vector``    ``}``    ``return` `0;``}`

Output

`4 is Present in the vector`

Time complexity: O(N).
Auxiliary Space: O(1).

## Linear Search Recursive Approach:

Follow the given steps to solve the problem:

• If the size of the array is zero then, return -1, representing that the element is not found. This can also be treated as the base condition of a recursion call.
• Otherwise, check if the element at the current index in the array is equal to the key or not i.e, arr[size – 1] == key
• If equal, then return the index of the found key.

Below is the implementation of the above approach:

## C++14

 `// C++ Recursive Code For Linear Search``#include ``using` `namespace` `std;` `int` `linearsearch(``int` `arr[], ``int` `size, ``int` `key)``{``    ``if` `(size == 0) {``        ``return` `-1;``    ``}``    ``else` `if` `(arr[size - 1] == key) {``        ``// Return the index of found key.``        ``return` `size - 1;``    ``}``    ``else` `{``        ``int` `ans = linearsearch(arr, size - 1, key);``        ``return` `ans;``    ``}``}` `// Driver's Code``int` `main()``{``    ``int` `arr = {5, 15, 6, 9, 4 };``    ``int` `key = 4;``  ` `      ``// Function call``    ``int` `ans = linearsearch(arr, 5, key);``    ``if` `(ans == -1) {``        ``cout << ``"The element "` `<< key << ``" is not found."``             ``<< endl;``    ``}``    ``else` `{``        ``cout << ``"The element "` `<< key << ``" is found at "``             ``<< ans << ``" index of the given array."` `<< endl;``    ``}``    ``return` `0;``}``// Code contributed by pragatikohli`

## Java

 `// Java Recursive Code For Linear Search``import` `java.io.*;` `class` `Test {``    ``static` `int` `arr[] = { ``5``, ``15``, ``6``, ``9``, ``4` `};` `    ``// Recursive Method to search key in the array``    ``static` `int` `linearsearch(``int` `arr[], ``int` `size, ``int` `key)``    ``{``        ``if` `(size == ``0``) {``            ``return` `-``1``;``        ``}``        ``else` `if` `(arr[size - ``1``] == key) {``            ``// Return the index of found key.``            ``return` `size - ``1``;``        ``}``        ``else` `{``            ``return` `linearsearch(arr, size - ``1``, key);``        ``}``    ``}` `    ``// Driver method``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `key = ``4``;` `        ``// Function call to find key``        ``int` `index = linearsearch(arr, arr.length, key);``        ``if` `(index != -``1``)``            ``System.out.println(``                ``"The element "` `+ key + ``" is found at "``                ``+ index + ``" index of the given array."``);` `        ``else``            ``System.out.println(``"The element "` `+ key``                               ``+ ``" is not found."``);``    ``}``}` `// This Code is submitted by Susobhan Akhuli`

## Python3

 `"""Python Program to Implement Linear Search Recursively"""`  `def` `linear_search(arr, key, size):``  ` `  ``# If the array is empty we will return -1``    ``if` `(size ``=``=` `0``):``        ``return` `-``1` `    ``elif` `(arr[size ``-` `1``] ``=``=` `key):``        ``# Return the index of found key.``        ``return` `size ``-` `1``    ``else``:``        ``return` `linear_search(arr, key, size ``-` `1``)`  `# Driver's code``if` `__name__ ``=``=` `"__main__"``:``    ``arr ``=` `[``5``, ``15``, ``6``, ``9``, ``4``]``    ``key ``=` `4``    ``size ``=` `len``(arr)``    ``ans ``=` `linear_search(arr, key, size)  ``# Calling the Function``    ``if` `ans !``=` `-``1``:``        ``print``(``"The element"``, key, ``"is found at"``,``              ``ans, ``"index of the given array."``)``    ``else``:``        ``print``(``"The element"``, key, ``"is not found."``)` `# Code Contributed By - DwaipayanBandyopadhyay``# Code is modified by Susobhan Akhuli`

## C#

 `// C# Recursive Code For Linear Search``using` `System;` `static` `class` `Test {``    ``static` `int``[] arr = { 5, 15, 6, 9, 4 };` `    ``// Recursive Method to search key in the array``    ``static` `int` `linearsearch(``int``[] arr, ``int` `size, ``int` `key)``    ``{``        ``if` `(size == 0) {``            ``return` `-1;``        ``}``        ``else` `if` `(arr[size - 1] == key) {``            ``// Return the index of found key.``            ``return` `size - 1;``        ``}``        ``else` `{``            ``return` `linearsearch(arr, size - 1, key);``        ``}``    ``}` `    ``// Driver method``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``int` `key = 4;` `        ``// Method call to find key``        ``int` `index = linearsearch(arr, arr.Length, key);` `        ``if` `(index != -1)``            ``Console.Write(``"The element "` `+ key``                          ``+ ``" is found at "` `+ index``                          ``+ ``" index of the given array."``);``        ``else``            ``Console.Write(``"The element "` `+ key``                          ``+ ``" is not found."``);``    ``}``}` `// This Code is submitted by Susobhan Akhuli`

## Javascript

 `// JavaScript Recursive Code For Linear Search` `let linearsearch = (arr, size, key) => {``  ``if` `(size == 0) {``    ``return` `-1;``  ``}``  ``else` `if` `(arr[size - 1] == key)``  ``{``  ` `    ``// Return the index of found key.``    ``return` `size - 1;``  ``}``  ``else``  ``{``    ``let ans = linearsearch(arr, size - 1, key);``    ``return` `ans;``  ``}``};` `// Driver Code``let main = () => {``  ``let arr = [5, 15, 6, 9, 4];``  ``let key = 4;``  ``let ans = linearsearch(arr, 5, key);``  ``if` `(ans == -1) {``    ``console.log(`The element \${key} is not found.`);``  ``} ``else` `{``    ``console.log(``      ```The element \${key} is found at \${ans} index of the given array.```    ``);``  ``}``  ``return` `0;``};` `main();` `// This code is contributed by Aman Singla...`

## PHP

 ``

## C

 `#include ` `// Define a function to perform the linear search``int` `linearSearch(``int` `arr[], ``int` `size, ``int` `key) {``  ``// If the size of the array is zero, return -1``  ``if` `(size == 0) {``    ``return` `-1;``  ``}` `  ``// Check if the element at the current index is equal to the key``  ``if` `(arr[size - 1] == key) {``    ``// If equal, return the index``    ``return` `size - 1;``  ``} ``else` `{``    ``// If not equal, call the function again with the size reduced by 1``    ``return` `linearSearch(arr, size - 1, key);``  ``}``}` `int` `main() {``  ``// Driver's code``  ``int` `arr[] = {5, 15, 6, 9, 4};``  ``int` `key = 4;``  ``int` `index = linearSearch(arr, ``sizeof``(arr) / ``sizeof``(``int``), key);``  ``if` `(index == -1) {``    ``printf``(``"Key not found in the array.\n"``);``  ``} ``else` `{``    ``printf``(``"The element %d is found at %d index of the given array \n"``,key,index);``  ``}``  ``return` `0;``}`

Output

`The element 4 is found at 4 index of the given array.`

Linear Search Complexity
 Linear search Complexity as given below:
Space Complexity
 Space complexity for linear search is O (n) as it does not use any extra space where
n is the number of elements in an array.
Time Complexity
 Best- case complexity = O (1) occurs when the search element is present at the first
element in the search array.
 Worst- case complexity = O (n) occurs when the search element is not present in the
set of elements or array.
 Average complexity = O (n) is referred to when the element is present somewhere
in the search array

Time Complexity: O(N)
Auxiliary Space: O(N), for using recursive stack space.

• Linear search is simple to implement and easy to understand.
• 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.

## Drawbacks of Linear Search:

• Linear search has a time complexity of O(n), which in turn makes it slow for large datasets.
• Not suitable for large array.
• Linear search can be less efficient than other algorithms, such as hash tables.

## When to use Linear Search:

• When we are dealing with a small dataset.
• When you need to find an exact value.
• When you are searching a dataset stored in contiguous memory.
• When you want to implement a simple algorithm.

## Summary:

• Linear search is a simple and flexible algorithm for finding whether an element is present within an array.
• It sequentially examines each element of the array.
•  The time complexity of linear search is O(n).
• It is used for searching databases, lists, and arrays.

My Personal Notes arrow_drop_up