Write an algorithm for linear search with an example.
Advertisements
प्रश्न
Write an algorithm for linear search with an example.
दीर्घउत्तर
Advertisements
उत्तर
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
या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
2023-2024 (July) Official Board Paper
