Sunday, March 24, 2024

BCA PART A 6. Implement a sequential search

 



def sequential_search(arr, target):
    """
    Perform a sequential search to find the target in the given list.
   
    Parameters:
        arr (list): The list to search in.
        target: The element to search for.
       
    Returns:
        int: The index of the target if found, otherwise returns -1.
    """
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

# Accepting input from the user
arr = input("Enter elements of the list separated by space: ").split()
arr = [int(x) for x in arr]  # converting input strings to integers

target = int(input("Enter the element to search for: "))

# Performing sequential search
result = sequential_search(arr, target)

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

Output :

Enter elements of the list separated by space: 1 3 45 6 8 90 Enter the element to search for: 3 Target 3 found at index 1.


Output 2:

Enter elements of the list separated by space: 3 5 7 89 -1 0 34 Enter the element to search for: 8 Target 8 not found in the list.






No comments:

Post a Comment