![]() |
VOOZH | about |
Linear Search checks each element of a list one by one until the desired element is found or the list ends. Given an array, arr of n elements, and an element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesn’t exist.
Examples:
Input: arr[] = [10, 50, 30, 70, 80, 20, 90, 40], x = 30
Output : 2
Explanation: For array [10, 50, 30, 70, 80, 20, 90, 40], the element to be searched is 30 and it is at index 2. So, the output is 2.
Explanation: A simple approach is to do a linear search, i.e
This takes an array arr and a target element to search. Iterates through each element of the array and compares it with the target. If the target is found, it returns its index; otherwise, it returns -1.
Element found at index: 3
It checks one element per recursive call and moves to the next index until it finds the target or reaches the end.
Element 30 found at index 2
Explanation:
Please refer complete article on Linear Search and Difference Between Recursive and Iterative Algorithms for more details!
This approach is useful when the list contains strings, and we want to search for a pattern (substring) using regular expressions.
Pattern found in element 'banana' at index 1
Explanation: