Python Program to Find Largest Element in an Array.

Given an integer array, the task is to write Python code to find the largest element present in the given array. 

Example:
Input: arr = [2, 3, 4, 1, 9, 5]
Output: Largest Element: 9

Input: arr = [1, 7, 2]
Output: Largest Element: 7

Determining the largest element in an array is a common task in Python programming. In this article, we will explore distinct approaches to finding the largest element in detail.

Find the largest Element in an Array Using Linear Search.

The linear search approach entails traversing the entire array sequentially, comparing each element to find the maximum.

Algorithm Steps:
  • Set a variable, initially holding the first element.
  • Iterate through each element of the given array.
  • For each element, compare it with the current maximum.
  • If a larger element is found, update the maximum.
  • Return the final maximum.

Python Code:
# Python code to find largest number of array
def find_largest(arr):
    max_element = arr[0]
    # Linear Search
    for element in arr:
        if element > max_element:
            max_element = element
    return max_element

arr = [2, 4, 9, 1]
print("Largest Number:", find_largest(arr))
Output:
Largest Number: 9
  • Time Complexity: O(n) where n is the number of elements present in the array.
  • Space Complexity: O(1) as no extra space is required to solve this problem.

Find the largest Element in an Array Using max() Function.

In this approach, we are using a built-in function max() to find the largest element of an array directly. 

Python Code:
# Python code to find largest number of array using max()
def find_largest(arr):
    return max(arr)

arr = [2, 4, 9, 10, 3]
print("Largest Number:", find_largest(arr))
Output:
Largest Number: 10
  • Time Complexity: O(n) where n is the size of the given array
  • Space Complexity: O(1) as no extra space is required.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS