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 C++.
Method 1: Using Iteration
This method iterates through the array to find the smallest and second smallest elements.
#include <iostream> #include <climits> using namespace std; void findSecondSmallest(int arr[], int n) { int smallest = INT_MAX, secondSmallest = INT_MAX; for (int i = 0; i < n; i++) { if (arr[i] < smallest) { secondSmallest = smallest; smallest = arr[i]; } else if (arr[i] < secondSmallest && arr[i] != smallest) { secondSmallest = arr[i]; } } cout << "Second Smallest Element: " << secondSmallest << endl; } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int n = sizeof(arr) / sizeof(arr[0]); findSecondSmallest(arr, n); return 0; }
Method 2: Using Sorting
This method sorts the array and takes the second element as the second smallest.
#include <iostream> #include <algorithm> using namespace std; void findSecondSmallest(int arr[], int n) { sort(arr, arr + n); cout << "Second Smallest Element: " << arr[1] << endl; } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int n = sizeof(arr) / sizeof(arr[0]); findSecondSmallest(arr, n); return 0; }
Method 3: Using Recursion
This method finds the second smallest element using recursion.
#include <iostream> #include <climits> using namespace std; void findSecondSmallestRecursive(int arr[], int n, int &smallest, int &secondSmallest) { if (n == 0) return; if (arr[n - 1] < smallest) { secondSmallest = smallest; smallest = arr[n - 1]; } else if (arr[n - 1] < secondSmallest && arr[n - 1] != smallest) { secondSmallest = arr[n - 1]; } findSecondSmallestRecursive(arr, n - 1, smallest, secondSmallest); } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int n = sizeof(arr) / sizeof(arr[0]); int smallest = INT_MAX, secondSmallest = INT_MAX; findSecondSmallestRecursive(arr, n, smallest, secondSmallest); cout << "Second Smallest Element: " << secondSmallest << endl; return 0; }