Python @ DjangoSpin

PyPro #59 Implementing Linear Search algorithm in Python

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Linear Search algorithm in Python

Linear Search algorithm in Python

Write a Python program to implement the Linear Search algorithm in Python.

Linear Search algorithm in Python

# Implementing Linear Search algorithm in Python

# Linear Search, also known as Sequential Search, looks for the target item by inspecting each
# item of an unsorted sequence until it finds the target item. If the target item is not found and the
# sequence is exhausted, the algorithm ends unsuccessfully.

# While this can be achieved easily using a for loop, it is advised against its use for building problem-solving skills. Use concepts of indexes and values at those indexes instead.

## PSEUDO CODE

##set currentIndex to 0
##set maxIndex to (length of sequence - 1)
##set targetElement to target value
##set targetElementFound to False
##
##while currentIndex is less than or equal to maxIndex AND targetElementFound is not True:
##    if element at data[currentIndex] is equal to targetElement:
##        set targetElementFound to True
##    else:
##        increment currentIndex by 1

# Sample data
data = [22, 45, 14, 38, 9]

currentIndex  = 0
maxIndex = len(data) - 1
targetElement = 38
targetElementFound = False

while currentIndex <= maxIndex and targetElementFound is not True:
    print("Checking element at index # {}".format(currentIndex))
    
    if data[currentIndex] == targetElement:
        print("Element {} found at index {}.".format(targetElement, currentIndex))
        targetElementFound = True
    else:
        currentIndex = currentIndex + 1

##Checking element at index # 0
##Checking element at index # 1
##Checking element at index # 2
##Checking element at index # 3
##Element 38 found at index 3.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply