Be the first user to complete this post
|
Add to List |
311. Linear Search Algorithm
Objective: Given an array [] of n elements and a element ‘x’, write a program to search an element ‘x’ in the array.
Example:
Input [] = {20, 30, 40, 10, 5, 2, 60, 73}, int x = 10 Output: Index 3 Input [] = {20, 30, 40, 10, 5, 2, 60, 73}, int x = 60 Output: Index 6 Input [] = {20, 30, 40, 10, 5, 2, 60, 73}, int x = 9 Output: No Found
Approach:
- Use a loop.
- Start from left most element in array.
- Check if element matches with x.
- If yes, we have found the element, return its position.
- Else move to next element in array and repeat from step 3.
- If all elements are scanned and none of the elements in array matches with x , means x is not present in array.
Time Complexity: O(N)
Next Article – Binary Search
Output:
Element 10 is found at index: Element 60 is found at index: 6 Element 9 is not found in array