Search

linear search by ON August 18 2019

Linear search is the simplest searching technique that checks each element one by one and if a match found then return the element. In other words, it looks down a list, one item at a time, without jumping.

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

int linearSearch(int arr[], int arrayLength, int key)
{

    for( int i = 0; i < arrayLength; i++ ) {
        // If key is match then return index of key.
        if ( arr[i] == key ) {
            return i;
        }
    }
    //If key is not exist in array.
    return -1;
}

int main() {

    // Array of elements.
    int arr[] = {1,4,7,11,16,19,23,28,30,31,40,78,105,201};

    // Length of array
    int arrayLength = sizeof( arr ) / sizeof( arr[0] );

    // Key that need to find in array.
    int key = 28;

    int index = linearSearch( arr,arrayLength, key );

    if ( index != -1 ) {
        cout<<"Found element at position : "<<index<<endl;
    } else {
        cout<<"Given element is not exist in array"<<endl;
    }

    return 0;
}

Key Points:-

  • Linear search is also called sequential search.
  • Linear search doesn’t require a sorted list like binary and jump search.
  • The time complexity of the linear search is O(n).
  • Linear Search only requires equality comparisons.
author's avatar ALL POST
Knowledge contribution is better than any contribution.

RELATED POST


1. binary search

BY August 18 2019

2. What is Jump search

BY August 18 2019
LEAVE A COMMENT

Leave a Reply

Your e-mail address will not be published. Required fields are marked *