×
>
<

Aptitude

Linear Search

Linear Search

Searching, in normal ways, can be coined as� to find the hidden thing�. In data structure.the searching algorithm is used to find whether a given number is present and if it is present then at what location it occurs.

There are two types of searching algorithm present in data structure through which searching any data become more easy.

  1. Linear search or sequential search
  2. Binary search

Linear Search Algorithm
Steps to Performe Linear Search

Step 1- Take array input and calculate the number of elements in the array call this as arr[]

Step 2- Take the input for the item to be searched in the array. Call this as item

Step 3- Linearly traverse the array using a for loop.

Step 4- For each array item check if arr[i] == item

  • If such condition is met print value and its position and return to the main function
  • If no such element is found and the whole array is traversed. Print not found

Code
  
#include<stdio.h>

void LinearSearch(int arr[], int len, int item)
{
    for(int i=0;i < len;i++)
    {
        if(arr[i] == item)
        {
        printf("%d Found at index %d", item, i);
        return;
        }
    }
    printf("Not Found");
}

int main() 
{
    int arr[] = {10, 20, 30, 40, 50};

    // calculating length of array 
    int len = sizeof(arr)/sizeof(arr[0]);

    // item to be searched
    int item = 40;
    LinearSearch(arr, len, item);

    return 0;
}
  
  
#include<iostream>
using namespace std;

void LinearSearch(int arr[], int len, int item){

    for(int i=0;i< len;i++){
        if(arr[i] == item){
            cout << item << " Found at index : " << i;
            return;
        }
    }
    cout << "Not found";
    
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};

    // calculating length of array 
    int len = sizeof(arr)/sizeof(arr[0]);

    // item to be searched
    int item = 40;
    LinearSearch(arr, len, item);

    return 0;
}
// space complexity: O(N)
// time complexity : O(N)
  
  
class Main {

    private static void LinearSearch(int[] arr, int item) {

        for(int i=0;i < arr.length;i++){
            if(arr[i] == item)
            {
                System.out.println(item + " Found at index : " + i);
                return;
            }
        }
        System.out.println("Not found");

    }

    public static void main(String args[]) {
        int[] arr = {10, 20, 30, 40, 50};

        int item = 40;
        LinearSearch(arr, item);
    }
}
// Space Complexity : O(N)
// Time Complexity : O(N)
	
	
40 Found at index 3
	
More about Linear Search
Pros

  • Very easy to understand and implement
  • Quick to write the code

Cons

  • Time complexity is bad O(n)

Time Complexity for Linear Search
BestAverageWorstSpace ComplexityAverage Comparision
O(1)O(n)O(n)O(1)(n+1)/2