English

Write an algorithm for linear search with an example. - Computer Science 1

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 10 with 30. (No match)
  • Step 2: Compare 50 with 30. (No match)
  • Step 3: Compare 30 with 30. (Match found!)
  • Result: Return Index 2.
def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1
shaalaa.com
  Is there an error in this question or solution?
2023-2024 (July) Official Board Paper

APPEARS IN

Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×