Finding the Maximum Element in a List
Given:
a = [12, 15, 2, 80, 40]
Method 1: Using the max()
Function
mx = max(a)
print("max =", mx)
# max= 80
This method finds the first largest element.
Time Complexity: O(n)
Method 2: Using the sort()
Method
Sort the list in ascending order and print the last element in the list.
a.sort()
print("max =", a[-1])
# max= 80
This method prints the last largest element.
Time Complexity: O(n log n)
Method 3: Using a for
Loop
Traverse all elements of the array one by one in a loop. If the current element of the array is greater than the previous largest element (stored in the variable mx
), store the new value of the largest element in mx
.
Option 1
mx = a[0]
for x in a:
if x > mx:
mx = x
print("max =", mx)
# max= 80
if a[i] > mx:
finds the first largest element.
if a[i] >= mx:
finds the last largest element.
Time Complexity: O(n)
Option 2
mx = a[0]
for i in range(len(a)):
if a[i] > mx:
mx = a[i]
print("max =", mx)
# max= 80
if a[i] > mx:
finds the first largest element.
if a[i] >= mx:
finds the last largest element.
Time Complexity: O(n)
You can also find the smallest element in the list using the given methods by utilizing the min()
function, sort()
function, or a for
loop.