Python Program for Linear Search
Question
Python Program for Linear Search
Solution
Sure, here is a simple Python program for linear search:
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linear_search(arr,x)))
In this program, we define a function linear_search that takes an array and the element you're searching for as inputs. It goes through each element of the array one by one (this is the "linear" part of "linear search") and checks if it's equal to the element you're searching for. If it is, it returns the index of that element. If it goes through the whole array and doesn't find the element, it returns -1.
The array we're searching through is arr, and the element we're searching for is x. After we call the linear_search function with arr and x as inputs, we print the index at which the element is found.
Similar Questions
Program to implement linear search.
Linear search(recursive) algorithm used in _____________
Write a pseudocode for linear search
Linear search(recursive) algorithm used in _____________ans.Never usedWhen the size of the dataset is largeWhen the dataset is unorderedWhen the size of the dataset is low Previous Marked for Review Next
what is linear search in data structures? give me the content for 5 marks
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.