31: Implement linear search in an unsorted array.
⏳⌚ 00:00:00

Question:-

Implement linear search in an unsorted array.
Example 1:
Input:
N=6, target = 3
arr[] = {1, 2 ,3, 5, 9, 10}
Output: 2nd index
Example 1:
Input:
N=6, target = 9
arr[] = {3, 5, 10, 12, 15, 18}
Output: Not found

Steps to solve:-

1. Function linearSearch:- The linearSearch function takes three parameters: the integer array arr[], the number of elements n, and the target element target.
It iterates through the array from the beginning (index 0) to the end (index n-1).
For each element in the array, it checks if the element is equal to the target.
If the target element is found, it returns the index where the element was found.
If the target element is not found after checking all elements, it returns -1 to indicate that the target is not in the array.
2. Main Function:- In the main function: The user inputs two values: n (the number of elements in the array) and target (the element to search for).
An integer array arr of size n is declared to store the input elements.
The user inputs n elements into the array.
The user also inputs the target element to search for.
The linearSearch function is called with the given array, number of elements, and the target element.
The result of the linear search is displayed:
If the target element is found, the code prints its index.
If the target element is not found, the code indicates that it's not present in the array.

solution->

View Code 1
Time Complexity = O(n)
Space Complexity = O(n)