Linear Search

23 Jun, 2022
Problem: Given an array arr[] of n elements, 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
Element x is present at index 6

Input : arr[] = {10, 20, 80, 30, 60, 50, 
                     110, 100, 130, 170}
           x = 175;
Output : -1
Element x is not present in arr[].
A simple approach is to do a linear search, i.e  
Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
If x matches with an element, return the index.
If x doesn’t match with any of the elements, return -1.
Example: 
C++
C
Java
Python3
C#
PHP
Javascript
// C++ code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 #include <iostream>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 codeint 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)        ? cout << "Element is not present in array"        : cout << "Element is present at index " << result;    return 0;}
// C code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 #include <stdio.h> 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 codeint 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 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 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 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 Codearr = [2, 3, 4, 10, 40]x = 10n = len(arr) # Function callresult = search(arr, n, x)if(result == -1):    print("Element is not present in array")else:    print("Element is present at index", result)
// C# code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1using 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 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// PHP code for linearly search x in arr[].// If x is present then return its location,// otherwise return -1 function search($arr, $x){    $n = sizeof($arr);    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, $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?>
<script> // Javascript code to linearly search x in arr[]. If x// is present then return its location, otherwise// return -1 function search(arr, n, x){    let i;    for (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)        ? document.write("Element is not present in array")        : document.write("Element is present at index " + result); // This code is contributed by Manoj </script>
Element is present at index 3
The time complexity of the above algorithm is O(n). 
Linear search is rarely used practically because other search algorithms such as the binary search algorithm and hash tables allow significantly faster searching compared to Linear search.
Improve Linear Search Worst-Case Complexity
if element Found at last  O(n) to O(1)It is the same as the previous method because here we are performing 2 ‘if’ operations in one iteration of the loop and in the last method we performed only 1 ‘if’ operation. This makes both the time complexities the same.
if element Found at last  O(n) to O(1)
It is the same as the previous method because here we are performing 2 ‘if’ operations in one iteration of the loop and in the last method we performed only 1 ‘if’ operation. This makes both the time complexities the same.
Below is the implementation:
C++14
Java
Python3
C#
Javascript
// C++ program for linear search#include<bits/stdc++.h>using namespace std; void search(vector<int> arr, int search_Element){    int left = 0;    int length = arr.size();    int position = -1;      int right = length - 1;           // Run loop from 0 to right    for(left = 0; left <= right;)    {                 // If search_element is found with        // left variable        if (arr[left] == search_Element)        {                         position = left;            cout << "Element found in Array at "                 << position + 1 << " Position with "                 << left + 1 << " Attempt";                            break;        }               // If search_element is found with        // right variable        if (arr[right] == search_Element)        {            position = right;            cout << "Element found in Array at "                 << position + 1 << " Position with "                 << length - right << " Attempt";                            break;        }        left++;        right--;    }     // If element not found    if (position == -1)        cout << "Not found in Array with "             << left << " Attempt";} // Driver codeint main(){    vector<int> arr{ 1, 2, 3, 4, 5 };    int search_element = 5;         // Function call    search(arr, search_element);}     // This code is contributed by mayanktyagi1709
// Java program for linear search import java.io.*; class GFG{     public static void search(int arr[], int search_Element)    {        int left = 0;        int length = arr.length;        int right = length - 1;        int position = -1;         // run loop from 0 to right        for (left = 0; left <= right;)        {                         // if search_element is found with left variable            if (arr[left] == search_Element)            {                position = left;                System.out.println(                    "Element found in Array at "                    + (position + 1) + " Position with "                    + (left + 1) + " Attempt");                break;            }                       // if search_element is found with right variable            if (arr[right] == search_Element)            {                position = right;                System.out.println(                    "Element found in Array at "                    + (position + 1) + " Position with "                    + (length - right) + " Attempt");                break;            }                         left++;            right--;        }         // if element not found        if (position == -1)            System.out.println("Not found in Array with "                               + left + " Attempt");    }           // Driver code    public static void main(String[] args)    {        int arr[] = { 1, 2, 3, 4, 5 };        int search_element = 5;               // Function call        search(arr,search_element);    }}
# Python3 program for linear searchdef search(arr, search_Element):    left = 0    length = len(arr)    position = -1    right = length - 1     # Run loop from 0 to right    for left in range(0, right, 1):         # If search_element is found with        # left variable        if (arr[left] == search_Element):            position = left            print("Element found in Array at ", position +                  1, " Position with ", left + 1, " Attempt")            break         # If search_element is found with        # right variable        if (arr[right] == search_Element):            position = right            print("Element found in Array at ", position + 1,                  " Position with ", length - right, " Attempt")            break        left += 1        right -= 1     # If element not found    if (position == -1):        print("Not found in Array with ", left, " Attempt") # Driver codearr = [1, 2, 3, 4, 5]search_element = 5 # Function callsearch(arr, search_element) # This code is contributed by Dharanendra L V.
// C# program for linear searchusing System;class GFG{     public static void search(int []arr,                              int search_Element)    {        int left = 0;        int length = arr.Length;        int right = length - 1;        int position = -1;         // run loop from 0 to right        for (left = 0; left <= right;)        {                         // if search_element is found with left variable            if (arr[left] == search_Element)            {                position = left;                Console.WriteLine(                    "Element found in Array at "                    + (position + 1) + " Position with "                    + (left + 1) + " Attempt");                break;            }                       // if search_element is found with right variable            if (arr[right] == search_Element)            {                position = right;                Console.WriteLine(                    "Element found in Array at "                    + (position + 1) + " Position with "                    + (length - right) + " Attempt");                break;            }                         left++;            right--;        }         // if element not found        if (position == -1)            Console.WriteLine("Not found in Array with "                               + left + " Attempt");    }           // Driver code    public static void Main(String[] args)    {        int []arr = { 1, 2, 3, 4, 5 };        int search_element = 5;               // Function call        search(arr,search_element);    }} // This code is contributed by 29AjayKumar
<script>     // Javascript program for linear search function search(arr, search_Element){    let left = 0;    let length = arr.length;    let right = length - 1;    let position = -1;     // Run loop from 0 to right    for(left = 0; left <= right;)    {                 // If search_element is found        // with left variable        if (arr[left] == search_Element)        {            position = left;            document.write(                "Element found in Array at " +                (position + 1) + " Position with " +                    (left + 1) + " Attempt");            break;        }                // If search_element is found        // with right variable        if (arr[right] == search_Element)        {            position = right;            document.write(                "Element found in Array at " +                (position + 1) + " Position with " +                (length - right) + " Attempt");            break;        }        left++;        right--;    }     // If element not found    if (position == -1)        document.write("Not found in Array with " +                       left + " Attempt");}      // Driver codelet arr = [ 1, 2, 3, 4, 5 ];let search_element = 5; // Function callsearch(arr, search_element); // This code is contributed by code_hunt </script>
Element found in Array at 5 Position with 1 Attempt
Time Complexity: O(n)
Auxiliary Space: O(1)
ALTERNATE APPROACH:
Recursive Approach For Linear Search:
The approach for the problem will be:
 The base case for the recursive code will be when the size of the given unsorted array will become zero, then the recursive call for the function will terminate and will start returning the values to the previous function calls in the recursion tree. Now, if the size of the given array is greater than zero then we will have two conditions:  
 The base case for the recursive code will be when the size of the given unsorted array will become zero, then the recursive call for the function will terminate and will start returning the values to the previous function calls in the recursion tree. 
Now, if the size of the given array is greater than zero then we will have two conditions:  
 If the element present at the current size index matches the given element, then return the index.
Else make a recursive call to the function by decreasing the array size by a factor of 1.
Below is the implementation for linear search using recursion:
C++
// Recursive Code For Linear Search#include <iostream>using namespace std;int linearsearch(int arr[], int size, int key){    if (size == 0)    {        return -1;    }    if (arr[size] == key)    {        return size;    }    else    {        int ans = linearsearch(arr, size - 1, key);        return ans;    }}int main() {    int arr[5]={1,5,6,9,4};    int key = 5;    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
The element 5 is found at 1 index of the given array.

Linear Search | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersLinear Search | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4GPdGsB3OSc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Also See – Binary Search
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.  
jit_t
RishabhPrabhu
DrRoot_
ApekshikPanigrahi
GaneshJ
abhishek07456cse
29AjayKumar
mayanktyagi1709
dharanendralv23
mank1083
code_hunt
arorakashish0911
rohanthakurarmy
susobhanakhuli
pragatikohli12
CBSE - Class 11
school-programming
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Maximum and minimum of an array using minimum number of comparisons
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number
Search, insert and delete in an unsorted array