OneBite.Dev - Coding blog in a bite size

find the minimum and maximum element in an array in python

Code snippet on how to find the minimum and maximum element in an array in python

def min_max(arr):
    minimum = arr[0]
    maximum = arr[0]
    for i in range(1, len(arr)):
        if arr[i] > maximum:
            maximum = arr[i]
        elif arr[i] < minimum:
            minimum = arr[i]
    return minimum, maximum

This code finds the minimum and maximum elements in an array. The code starts by assigning the first element of the array to both the minimum and maximum variables. Then a loop iterates over the remaining elements in the array, one element at a time. If the current element is greater than the maximum, it is assigned to the maximum variable. If the current element is less than the minimum, it is assigned to the minimum variable. At the end of the iteration, the minimum and maximum variables will hold the desired values. Finally, the function returns the values of the minimum and maximum variables.

python