Three different ways to find the maximum and minimum elements in the list
We can find maximum and minimum elements in the list using a general procedure or by using some built-in functions in python, we have to know about how the built-in functions work, so, in this blog, I will tell you the different ways to find maximum and minimum elements
the time complexity for all the ways I have mentioned is O(n)
1.General procedure to find max and min elements in a list
At first, we are considering the first element was max and min value and then we iterate through the given list and compare to the max and min values, if the element from the list was greater than the max value then we have to update the max value, for a min, it follows the same procedure as max but the change is, we have to update the min which is smaller than the element if we write code for the above logic it looks like this
list=[5,2,10,-3,15,54]
max=list[0]
min=list[0]
for ele in list:
if(ele>max):
max=ele
elif(ele<min):
min=ele
print(max,min)
Output:
54 -3
Time complexity: O(n)
2.Using the built-in functions in python
In python, we have some built-in methods to find max and min elements in the list, the min() method returns the lowest value in the list, we can apply these methods on the list contains the strings returns the lowest based on the alphabetical order
ist=[5,2,10,-3,15,54]
maxi=max(list)
mini=min(list)
print(maxi,mini)
Output:
54 -3
Time complexity: O(n)
3.Using the sort built-in functions in python
we can also find the min and max elements using the sort() method, the sort method rearranges the elements present in the list in ascending order, so, we can easily find max and min values in the list by printing the first and last element in the list
list=[5,2,10,-3,15,54]
list.sort()
print(list[-1],list[0])
Output:
54 -3
Time complexity: O(nlogn)