Linear search

array data structures

Let's populate an array with random integers:

0123456

As you can see we can search for an item in an array data structure. We start at the first element and step through the array looking for the item.

This is known as linear search. There are a few different strategies for performing Linear Search. Here are two:

Strategy 1: use a FOR LOOP

found = False

searchItem = int(input("Enter a search item: "))

for i in range (len(numArray)):

if numArr[i] = searchItem:

found = True

#end of loop

if found == False

print(f"{searchItem} is not in the array!")

else:

print(f"{searchItem} is in the array!")

Strategy 2: use a WHILE LOOP

i = 0

searchItem = int(input("Enter a search item: "))

while numsArray[i] != searchItem:

i++

#end of loop

if i == len(numsArray):

print(f"{searchItem} is not in the array!")

else:

print(f"{searchItem} is in the array!")

Task

Open the worksheet and complete the tasks.

Tags

data type INTEGER pseudocode ← array assign STRING index linear search BOOLEAN variable


Feelings

How do you feel right now?