Find Second Smallest Element in an Array
Understanding Second Smallest Element
Finding the second smallest element in an array involves identifying the smallest element and then searching for the next smallest value.
We will explore three different methods to find the second smallest element in an array using Python.
Method 1: Using Iteration
This method iterates through the array to find the smallest and second smallest elements.
def find_second_smallest(arr): smallest, second_smallest = float('inf'), float('inf') for num in arr: if num < smallest: second_smallest = smallest smallest = num elif num < second_smallest and num != smallest: second_smallest = num print("Second Smallest Element:", second_smallest) arr = [10, 20, 4, 45, 99, 23] find_second_smallest(arr)
Method 2: Using Sorting
This method sorts the array and takes the second element as the second smallest.
def find_second_smallest(arr): arr.sort() print("Second Smallest Element:", arr[1]) arr = [10, 20, 4, 45, 99, 23] find_second_smallest(arr)
Method 3: Using Recursion
This method finds the second smallest element using recursion.
def find_second_smallest_recursive(arr, n, smallest, second_smallest): if n == 0: return smallest, second_smallest if arr[n - 1] < smallest: second_smallest = smallest smallest = arr[n - 1] elif arr[n - 1] < second_smallest and arr[n - 1] != smallest: second_smallest = arr[n - 1] return find_second_smallest_recursive(arr, n - 1, smallest, second_smallest) arr = [10, 20, 4, 45, 99, 23] smallest, second_smallest = find_second_smallest_recursive(arr, len(arr), float('inf'), float('inf')) print("Second Smallest Element:", second_smallest)