sort(arr, arr + n)
in C++).#include <iostream>
#include <algorithm>
using namespace std;
void findSecondSmallestBySorting(int arr[], int n) {
sort(arr, arr + n);
cout << "The second smallest element is: " << arr[1] << endl;
}
int main() {
int arr[] = {12, 3, 5, 7, 19};
int n = sizeof(arr) / sizeof(arr[0]);
findSecondSmallestBySorting(arr, n);
return 0;
}
[12, 3, 5, 7, 19]
Output: The second smallest element is: 5
first_smallest
).first_smallest
(second_smallest
).first_smallest
).first_smallest
, to find the second smallest element (second_smallest
).second_smallest
.#include <iostream>
#include <climits>
using namespace std;
void findSecondSmallestTwoPass(int arr[], int n) {
int first_smallest = INT_MAX, second_smallest = INT_MAX;
// First traversal to find the smallest element
for (int i = 0; i < n; i++) {
if (arr[i] < first_smallest) {
first_smallest = arr[i];
}
}
// Second traversal to find the second smallest element
for (int i = 0; i < n; i++) {
if (arr[i] > first_smallest && arr[i] < second_smallest) {
second_smallest = arr[i];
}
}
cout << "The second smallest element is: " << second_smallest << endl;
}
int main() {
int arr[] = {12, 3, 5, 7, 19};
int n = sizeof(arr) / sizeof(arr[0]);
findSecondSmallestTwoPass(arr, n);
return 0;
}
[12, 3, 5, 7, 19]
Output: The second smallest element is: 5
first_smallest
and second_smallest
to a very large value (e.g., INT_MAX
).first_smallest
, update second_smallest
to first_smallest
and first_smallest
to the current element.first_smallest
but smaller than second_smallest
, update second_smallest
.second_smallest
.#include <iostream>
#include <climits>
using namespace std;
void findSecondSmallestSinglePass(int arr[], int n) {
int first_smallest = INT_MAX, second_smallest = INT_MAX;
for (int i = 0; i < n; i++) {
if (arr[i] < first_smallest) {
second_smallest = first_smallest;
first_smallest = arr[i];
} else if (arr[i] > first_smallest && arr[i] < second_smallest) {
second_smallest = arr[i];
}
}
cout << "The second smallest element is: " << second_smallest << endl;
}
int main() {
int arr[] = {12, 3, 5, 7, 19};
int n = sizeof(arr) / sizeof(arr[0]);
findSecondSmallestSinglePass(arr, n);
return 0;
}
[12, 3, 5, 7, 19]
Output: The second smallest element is: 5
first_smallest
and second_smallest
.