Find Largest Element in an Array
Understanding Finding Largest Element
Finding the largest element in an array involves scanning the array and keeping track of the maximum value encountered.
We will explore three different methods to find the largest element in an array using Python.
Method 1: Using Iteration
This method iterates through the array and finds the largest element.
def find_largest(arr): max_val = arr[0] for num in arr: if num > max_val: max_val = num return max_val arr = [10, 20, 4, 45, 99, 23] print("Largest element:", find_largest(arr))
Method 2: Using Sorting
This method sorts the array and takes the last element as the largest.
def find_largest(arr): arr.sort() return arr[-1] arr = [10, 20, 4, 45, 99, 23] print("Largest element:", find_largest(arr))
Method 3: Using Recursion
This method finds the largest element using recursion.
def find_largest(arr, n): if n == 1: return arr[0] return max(arr[n-1], find_largest(arr, n-1)) arr = [10, 20, 4, 45, 99, 23] print("Largest element:", find_largest(arr, len(arr)))