Movatterモバイル変換


[0]ホーム

URL:


Skip to content
May 24, 2025
Latest
Home »Python program to implement Linear Search Algorithm
Python program to implement Linear Search Algorithm
Python program to implement Linear Search Algorithm

Hello everyone, welcome back toProgramming In Python! Here I am going to explain to you how to implement a linear search algorithm in Python. This linear search is a basic search algorithm that searches all the elements in the list and finds the required value. This is also known as a sequential search.

Here in this technique, I compare each and every element with the key element to be found, if both of them match, the algorithm returns that element is found and its position.

Master the basics of data analysis in Python. Expand your skillset by learning scientific computing with numpy.

Take the course on Introduction to Python onDataCamp herehttps://bit.ly/datacamp-intro-to-python

You can also watch the video on YouTubehere

Program on GitHub

Code Visualization – Linear Search Algorithm

Time Complexity

Best CaseO(1)
Average CaseO(n)
Worst CaseO(n)

Program on GitHub

Algorithm

Given a listL of `n` elements with values or records,L0 ... Ln-1 and key/target elementK, linear search is used to find the index/position of the targetK in list L

  1. Initialize a boolean variablefound and set it to False initially
  2. Start for loop withi ranging from 0 to the length of the list
  3. Check if key element is equal toL[i]
    1. if equals
      1. set found boolean variable to `True`
      2. print the position of the element found
      3. break for loop
  4. If the boolean variablefound is equal toFalse after for loop, print that the element is not found in the list

Program on GitHub

Ad:
Learn Python Programming Masterclass–Enroll Now.
Udemy

Program

__author__ = 'Avinash'lst = []num = int(input("Enter size of list: \t"))for n in range(num):    numbers = int(input("Enter any number: \t"))    lst.append(numbers)x = int(input("\nEnter number to search: \t"))found = Falsefor i in range(len(lst)):    if lst[i] == x:        found = True        print("\n%d found at position %d" % (x, i))        breakif not found:    print("\n%d is not in list" % x)

Program on GitHub

Output

Linear Search Algorithm in Python
Linear Search Algorithm in Python

Linear Search Algorithm in Python

Know about one more search algorithm calledBinary Search, you can learn about ithere.

Online Python Compiler

Leave a ReplyCancel reply

Your email address will not be published.Required fields are marked*

Special Offer

Subscribe to our newsletter!

Great Deals

Ads

Categories


[8]ページ先頭

©2009-2025 Movatter.jp