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