Write a python program to implement linear search.
Added 2 weeks ago
Active
Viewed 20
Ans

# Function to perform Linear Search
def linear_search(arr, target):
    # Loop through the list to find the target
    for i in range(len(arr)):
        if arr[i] == target:
            return i  # Return the index of the target element
    return -1  # Return -1 if the element is not found

# Example usage
arr = [10, 20, 30, 40, 50]
target = 30

# Perform linear search
result = linear_search(arr, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")

Sample Output
Element 30 found at index 2



Related Questions