Menu

Search Algorithms

Flags in Linear Search

A flag is a Boolean variable that records whether something has happened. In a linear search, a flag called found lets the loop stop the moment the target appears, instead of checking every remaining item.

Ending the loop when the target is found

Set found to False before the loop. On each pass, compare the current item with the target and set found = True if they match. The loop condition while not found and index < len(items) then ends the search immediately. The flag is needed because the loop must know a match has happened before it decides whether to continue, and it also records the result after the loop so the not-found case can be handled.

Ending early in sorted data

If the list is sorted in ascending order, an item greater than the target means the target cannot appear later. A second flag, too_far, records that the search has moved beyond the position where the target would sit, and ends the loop early. In a descending list the test is reversed: the search stops when an item is smaller than the target, because the target cannot appear after that point.

Looking up product code 237 in this sorted stock list: at index 3 the code 241 is greater than 237, so too_far becomes True and the loop ends after four passes through the loop — code 237 is not stocked.

A flowchart of the while loop with found and too_far flags: the loop runs while neither flag is set and index is in range, setting found when the code matches, too_far when it is greater, and otherwise adding 1 to index. A strip shows 204, 219, 233, 241 with too_far set at index 3 when searching for 237.

IndexCodeTestfoundtoo_far
0204204 == 237? No; 204 > 237? NoFalseFalse
1219219 == 237? No; 219 > 237? NoFalseFalse
2233233 == 237? No; 233 > 237? NoFalseFalse
3241241 == 237? No; 241 > 237? YesFalseTrue
codes = [204, 219, 233, 241, 258, 266, 281]
target = int(input("Product code: "))
found = False
too_far = False
index = 0
while not found and not too_far and index < len(codes):
    if codes[index] == target:
        found = True
    elif codes[index] > target:
        too_far = True
    else:
        index = index + 1
if found:
    print("Code " + str(target) + " in stock")
else:
    print("Code " + str(target) + " not stocked")

Output when the user types 237:

Product code: 237
Code 237 not stocked

A for loop can be written with a flag that skips the rest of the work once a match is found, but it still passes through the remaining items; a while loop with flags can stop at the right moment, so choose it when efficiency matters.

Practise this