Find Maximum/Minimum

Search through a list of values, looking for either:

  • the largest/smallest value, or
  • the location (index) of the largest/smallest value

General Algorithms

Algorithms for finding the minimum are the same, but replacing “>” with “<“, and a change in the variable names.

Find largest value

max = first item in list
for index = rest of list
    if list[index] > max then
        max = list[index]
    end if
next item

Find index of largest value

max = 0
for index = remaining items in list
    if list[index] > list[max] then
        max = index
    end if
next item

Examples

Find largest value

#
tallestHeight = heights[0]
 
for mountain in range(1,len(heights)):
 
    if heights[mountain] > tallestHeight:
        tallestHeight = heights[mountain]
 
print(f"Tallest height = {tallestHeight }")
# 

Find index of largest value

#
tallest = 0
 
for mountain in range(1,len(heights)):
 
    if heights[mountain] > heights[tallest]:
        tallest = mountain
 
print(f"The tallest mountain is {names[tallest]}")
#