Linear Search Algorithm.
Introduction:
In this tutorial, we will be learning what is Linear Search Algorihtm and how it is used with an Algorihtm code. So, I'm assuming that you have a good knowledge of Arrays, Loops. Because we will be using Loops and Arrays during this process.
Linear Search: Linear as name suggest which is one by one linearly in one direction. So, Linear Search is used for searching an element in an array linearly one by one. In Linear Search we iterate over each element one by one and when an element is found we return its index. If we have not found element in array we can return -1.
Example:
Output: 1
(because index of 3 is 1)
Input: arr[] = { 2, 3, 4, 6, 10 }, x = 15
Output: -1
(because 15 is not found in array)
Now Let's have a quick look on steps/algorithm of LINEAR SEARCH.
Algorithm:
- Start a loop starting from index i=0 which goes until i < n (Here n is size of Array).
- If arr[i] matches with element (which is to be searched).
- return i.
- Otherwise, return -1.
- At Last, Loop ends.
Output:
Complexity Analysis:
Time Complexity: O(n), In worst case time complexity of this algorithm can go upto O(n) as we have to traverse whole array.
Space Complexity: O(1), we have not used any extra space.