Advertisements
Advertisements
Question
Write an algorithm for linear search with an example.
Long Answer
Advertisements
Solution
Linear search is the simplest searching algorithm. It checks every element in a list one by one until it finds the target value or reaches the end.
Example:
List: [10, 50, 30, 70, 80]
Target: 30
- Step 1: Compare
10with30. (No match) - Step 2: Compare
50with30. (No match) - Step 3: Compare
30with30. (Match found!) - Result: Return Index
2.
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1shaalaa.com
Is there an error in this question or solution?
2023-2024 (July) Official Board Paper
