Problem Link - Linear Search
Problem Statement:
How Linear Search Works
Approach:
The solution uses linear search, which checks each element in the array to find a specified value.
-
Define the Array: An array
{3, 5, 2, 9, 7, 1}is created for searching. -
Calculate Length: The length of the array is determined to know how many elements to check.
-
Search for the Value: A boolean variable
foundis initialized tofalseto track if the value(7)is present.- A
forloop iterates over each element:- If the current element equals 7,
foundis set totrue, and the loop exits.
- If the current element equals 7,
- A
-
Print the Result: After the loop, if
foundistrue, it prints “Yes”; otherwise, it prints “No”.
Linear search checks each item sequentially until it finds the target or reaches the end of the array.
Time Complexity:
- O(n), where n is the number of elements. We may check each element once.
Space Complexity:
- O(1), using a constant amount of space regardless of the array size.