Linear Search

 Linear Search or Simple Search

Aim:   To find if an element (number, character, or string ) exist in a given list and its position.

How Algorithm works: 

* Linear search sequentially checks every element of the list and compares it with the target value until it matches. 

* If the algorithm reaches the end of the list, the search terminates.

Pseudocode:

Linear Search ( Array A, Target T )

  1. For i = 1 to n
  2.     if (A[i] = T)
  3.         print response "Number found at position i " and Exit
  4. print response "Number not found"
  5. Exit
C++ Code:
#include<iostream>
using namespace std;

template<size_t N>
void linearSearch(int (&array)[N], int target)
{
    for(int i = 0; i < N; i++) {
        if(array[i] == target) {
            cout<<"Target found at position : "<<i+1;
            return;
        }
    }
    cout<<"Target not found";

}
int main(){
    int array[] = {10 , 30, 50, 60, 80, 90, 100};
    int target = 20;
    linearSearch(array, target);
}

Time Complexity:
The time complexity of the above code will be O(n) where n is the size of an array.

Comments

Post a Comment

Popular posts from this blog

Multiply Strings Leetcode 43 question Correct Solution

In the following table, there are 12 entries in the form nij, where i = 1, 2, 3 and j 1,2,3,4. Each of these entries denotes the largest integer n such that f(n) milliseconds = does not exceed t, where f(n) is the function corresponding to the row of the entry and t is the time corresponding to the column of the entry. For example, for entry n32, we have f(n) = 2^n and t = 1 minute. Hence n32 should be the largest integer n such that 2^n milliseconds is no more than 1 minute.

Longest Palindromic Substring Solution