Understand what is Linear Search algorithm, proper use & with its Time Complexity.
Linear Search Algorithm is a very simple and basic search algorithm. It is a sequential search type algorithm. It compares with each and every element until a match is found. It searches in an iterative manner i.e works with loops (for loop, while loop) otherwise the search continues.
Linear Search Algorithm working
So this is how this Linear Search Algorithm works, it compares each element with the element we want to search and continues to search until the match founds once the match is found then exit from this algorithm.
Algorithm
- st Step: Start.
- nd Step: Declare an array as 'arr' and variables flag, i, n.
- rd Step: initialize array elements and flag as zero.
- th Step: assign the number that is to be search in the 'n' variable.
- th Step: assign "for loop" with the length of array
- th Step: if condition when arr[i] == n.
- th Step: when above condition true flag = 1 and breakthrough loop, display "match found".
- th Step: else flag = 0 and display "match not found".
- th Step: Stop.
// C Language Code void linearSearch(int arr[], int n, int len) { //int n = 10
int i = 0;
for(i = 0; i<len; i++) { if(arr[i] == n) { print("Match Found at index %d",i); } else{ print("Match not Found"); } } }
// Python Code lst = [2,4,7,9,10,5] findElement = 10 for i in lst: if findElement == i: print("Match Found at index ",lst.index(i)) else: print("Match not Found")
Output :
Match Found at index 4.
Comments
Post a Comment