Linear Search Algorithm

Objective: Given an array [] of n elements and a element ‘x’, write a program to search an element ‘x’ in the array.

Example:

Input [] = {20, 30, 40, 10, 5, 2, 60, 73}, int x = 10
Output: Index 3

Input [] = {20, 30, 40, 10, 5, 2, 60, 73}, int x = 60
Output: Index 7

Input [] = {20, 30, 40, 10, 5, 2, 60, 73}, int x = 9
Output: No Found

Approach:

  1. Use a loop.
  2. Start from left most element in array.
  3. Check if element matches with x.
    1. If yes, we have found the element, return its position.
    2. Else move to next element in array and repeat from step 3.
  4. If all elements are scanned and none of the elements in array matches with x , means x is not present in array.

Time Complexity: O(N)

Next Article – Binary Search

Code:



Output:

Element 10 is found at index: 
Element 60 is found at index: 6
Element 9 is not found in array

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: