DEV Community

Abirami Prabhakar
Abirami Prabhakar

Posted on

To Find the max & min elements in a array

here to find the minimum and maximum element in a array without using the minimum and maximum function, we are comparing all the elements to its previous element find the max and min value and then, the elements are returned back in a list with a use of simple for loop

Intially,
min -> arr[0]
max -> arr[0]

in a for loop -> i++
in a linear span compared to its element in list in loop

arr[i] >< min or arr[i] >< max

lets have a look into the code block,

def minmax(arr):
    min = arr[0]
    max = arr[0]

    for i in range (1,len(arr)):
        if arr[i] < min:
           min = arr[i]
        elif arr[i] > max:
           max = arr[i]
    return [min,max]
arr = [12, 3, 15, 7, 9]
print(minmax(arr))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)