Showing posts with label Linear search. Show all posts
Showing posts with label Linear search. Show all posts

Friday, 6 December 2019

Linear search-Algorithm and Program of linear search


Linear search is also known as Sequential search.It is most popular and widely used searching algorithm.It does not require sorted array to search elements.

  Space complexity:  O(1)

  Time complexity:
Best case
Average case
Worst case
O(1)
O(n)
O(n)






Algorithm of linear search:

Step 1: Set i to 1 
Step 2: if i > n then go to step 7 
Step 3: if A[i] = x then go to step 6 
Step 4: Set i to i + 1 
Step 5: Go to Step 2 
Step 6: Print Element x Found at index i and go to step 8 
Step 7: Print element not found 
Step 8: Exit



Program of linear search:

#include<iostream>
 using namespace std;
   int main()

{
  int array[100], search, i, n;

  cout<<"Enter number of elements in array \n";
  cin>>n;

  cout<<"Enter integers \n";

  for (i=0; i<n; i++)
    cin>>array[i];

  cout<<"Enter a number to search \n";
    cin>>search;

  for (i=0; i<n; i++)
  {
    if (array[i] == search)    /* If required element is found */
    {
      cout<<"value is present at location:"<<i+1;
      break;
    }
  }
  if (i == n)
    cout<<" value isn't present in the array. \n";
  return 0;
}

Output:
Output of linear search