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