Linear search algorithm python – Linear Search in Python

Linear search algorithm python: Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Linear Search works in much the same way as we search for a random list of objects.

If we need to find a word on a specific page, we will begin at the top and go through each word one by one before we find the word we are searching for.

Linear Search:

Linear search in python: Linear search is a method for locating elements in a sequence. It’s also known as a sequential scan. It is the most basic searching algorithm since it searches for the desired element sequentially.

It compares each element to the value that we are looking for. If both match, the element is found, and the algorithm returns the index position of the key.

Examples:

Input:

given_elements =[2, 7, 3, 4, 9, 15]   key= 9

Output:

Element 9 is found at index 4

Linear Search in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Algorithm

  • Begin with the leftmost element of the given list and compare element “key” with each element of the list one by one.
  • Return the index value if “key” matches any of the elements.
  • If “key” does not match any of the elements in list [], return -1 or the element was not found.

2)Implementation

Below is the implementation of linear search:

# function which return index if element is present else return -1
def linearSearch(given_list, key):
    # Traverse the list
    for index in range(len(given_list)):
        # if the element is equal to key then return index
        if(given_list[index] == key):
            return index
    # if no index is returned then the element is not found in list
    # return -1
    return -1


# given_list
given_list = [2, 7, 3, 4, 9, 15]
# given key
key = 9
# passing the given_list and key to linearSearch function
res = linearSearch(given_list, key)
# if result is equal to -1 then element is not present in list
if(res == -1):
    print("Given element(key) is not found in list")
else:
    print("Element", key, "is found at index", res)

Output:

Element 9 is found at index 4

3)Time Complexity

Python linear search: Linear Search is not an efficient algorithm since it goes through each item in the list, so the number of items in the list has a direct effect on the algorithm.

To put it another way, the algorithm has a time complexity of O. (n). This means that if the number of items in the list is increased by a certain amount, the time required to complete the algorithm will also be multiplied by the same amount.
Related Programs: