Higher – Find Maximum and Find Minimum Standard Algorithms

We spent a lot of last week on Standard Algorithms, most of them have the structure of an IF inside a FOR loop. While it is possible to use a FOR EACH loop this would mean that we could not know what the position was of the value we were searching for. In the examples below the returned value (max or min) could be changed to the position to allow this to be used elsewhere in the program.

To find the largest number in an array we would use the “Find Maximum” algorithm

def findMax(numbers):
    # Find biggest number
    max=numbers[0]
    for counter in range(1,len(numbers)):
        if numbers[counter]>max:
            max=numbers[counter]
            #position=counter
    return max

To find the smallest number in an array we would use the “Find Minimum” algorithm

def findMin(numbers):
    #Find smallest number
    min=numbers[0]
    for counter in range(1,len(numbers)):
        if numbers[counter]<min:
            min=numbers[counter]
            #position=counter
    return min

Notice that both of these functions are very similar with only the operator changing. Did you also notice that the for loop starts from index 1? Why do you think this is?

Leave a Reply

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