Finding the maximum element in an array using python
Description: In this blog post, we will explore how to find the maximum number in an array using Python. We will cover a single algorithm that loops through each element in an array and keeps track of the maximum element seen so far.
Let's start with an example:
arr = [3, 5, 1, 8, 2]
We are to find the maximum element in the above array. One of the ways to do this is to loop through each element in the array and keep track of the maximum element seen so far.
Here is an example Python function that implements this algorithm :
def find_max(arr): max_elem = arr[0] for elem in arr: if elem > max_elem: max_elem = elem return max_elem
The following steps below explain the function :
We start by initializing max_elem to be the first element in the array:
max_elem = arr[0]
Next, we loop through each element in the array using a for loop:
for elem in arr:
For each element in the array, we check if it's greater than max_elem:
If elem > max_elem:
If elem is greater than max_elem, then we update max_elem to be elem:
max_elem = elem
Finally, we return max_elem:
return max_elem
We test this function with our example array:
arr = [3, 5, 1, 8, 2]. max_elem = find_max(arr). Print max_elem(). # output: 8
As expected, the function returns 8, which is the maximum element in the array.
In conclusion, finding the maximum in an array using Python is a task that can be solved using a for loop and a variable to keep track of the maximum element seen so far. The algorithm has a time complexity of O(n), where n is the number of elements in the array.
You can contact me on Twitter via: https://twitter.com/Chiomcer_Igwe