Computer Science, asked by annviyacv, 4 months ago

write a python script to input anumber and peform linear search

Answers

Answered by yadavjii64
2

Answer:

Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].

Examples :

Input : arr[] = {10, 20, 80, 30, 60, 50,

110, 100, 130, 170}

x = 110;

Output : 6

Element x is present at index 6

Input : arr[] = {10, 20, 80, 30, 60, 50,

110, 100, 130, 170}

x = 175;

Output : -1

Element x is not present in arr[].

A simple approach is to do linear search, i.e

Start from the leftmost element of arr[] and one by one compare x with each element of arr[]

If x matches with an element, return the index.

If x doesn’t match with any of elements, return -1.

Answered by jai696
1

\large\mathsf\color{pink}{Solution\: using\: python\: 3}

def linear_search(arr, n):

for idx, x in enumerate(arr):

if x == n:

return idx

return -1

# populate an array to linear search

arr = [int(n) for n in range(1, 1001)]

n = int(input("enter number: "))

idx = linear_search(arr, n)

print(f"found at idx: {idx}") if idx > -1 else print("not found")

\large\mathsf\color{lightgreen}useful?\: \color{white}\longrightarrow\: \color{orange}brainliest!

Similar questions