Problem
Given an array of n elements and a element ‘x’, write a program to search an element ‘x’ in the array.
Examples
|
|
Solution
Algorithm
- Begin with the leftmost element of the array.
- Check if the element matches ( x ).
- If it matches, return its position.
- If not, move to the next element and repeat the process.
- If all elements are checked and none match ( x ), then ( x ) is not in the array.
Here is the dry run below:
Code
Java
|
|
Python
|
|
Time Complexity Analysis
Time Complexity
O(n) where n
is number of elements in array
Space Complexity
O(1) as we dont use any extra space.