Linear Search: Data Structure and Algorithm

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 5

LINEAR SEARCH

Data structure and Algorithm


LINEAR SEARCH
Linear search is a very simple search algorithm. In this type of
search, a sequential search is made over all items one by one. Every
item is checked and if a match is found then that particular item is
returned, otherwise the search continues till the end of the data
collection.
 Linear search is rarely used practically because other search algorithms such as
the binary search algorithm and hash tables allow significantly faster-searching
comparison to Linear search.
ALGORITHM
Linear Search ( Array A, Value x)
=> This algorithm is used to implement linear search
Step 1: Set i to 0
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
C++ PROGRAM
 #include <iostream> { 

 using namespace std;     int arr[5] = { 2, 3, 4, 10, 40 };

   int search(int arr[], int n, int x)     int x = 10;

 {     int n = 5 // size of array

     int i;     // Function call

     for (i = 0; i < n; i++)     int result = search(arr, n, x);

         if (arr[i] == x)     if(result == -1)

             return i;          cout << “Element is not present in array” ;

     return -1;      else cout << “Element is present at index “ << result;

 }     return 0;

   // Main function  }

 int main(void)
TIME COMPLEXITY
A linear search scans one item at a time, without jumping to any item
The worst case complexity is O(n), sometimes known an O(n) search
 Time taken to search elements keep increasing as the number of elements are
increased.
Worst-case performance
O(n)
Best-case performance
O(1)
Average performance
O(n/2)

You might also like