Linear Search
Linear Search or Simple Search
Aim: To find if an element (number, character, or string ) exist in a given list and its position.
How Algorithm works:
* Linear search sequentially checks every element of the list and compares it with the target value until it matches.
* If the algorithm reaches the end of the list, the search terminates.
Pseudocode:
Linear Search ( Array A, Target T )
- For i = 1 to n
- if (A[i] = T)
- print response "Number found at position i " and Exit
- print response "Number not found"
- Exit
#include<iostream> using namespace std; template<size_t N> void linearSearch(int (&array)[N], int target) { for(int i = 0; i < N; i++) { if(array[i] == target) { cout<<"Target found at position : "<<i+1; return; } } cout<<"Target not found"; } int main(){ int array[] = {10 , 30, 50, 60, 80, 90, 100}; int target = 20; linearSearch(array, target); }
Time Complexity:
The time complexity of the above code will be O(n) where n is the size of an array.
Share if you like
ReplyDelete