Open In App

How to Find the Second Smallest Element in an Array in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, arrays are data structures that store the collection of data elements of the same type in contiguous memory locations. In this article, we will learn how to find the second smallest element in an array in C++.

Example:

Input:
myArray = {10, 5, 8, 2, 7, 3, 15};

Output:
The second smallest element in the array is: 3

Finding the Second Smallest Element in an Array in C++

To find the second smallest element in the array, we will have to iterate the array and keep the track of current smallest and second smallest values. The below approach shows how to do it.

Algorithm

  • Initialize two variables smallest and secondSmallest first array element.
  • Traverse through each element of the array.
  • For each element in the array:
    • If the element is smaller than smallest update secondSmallest with the current value of smallest and update smallest with the current array value.
    • If the element is not smaller than the smallest but smaller than secondSmallest then update the value of secondSmallest.
  • Return secondSmallest which holds the value of the second smallest element in the array.

C++ Program to Find the Second Smallest Element in an Array

The following program illustrates how we can find the second smallest element in an array in C++.

C++
// C++ Program to how to find the second smallest element in
// an array
#include <climits>
#include <iostream>
using namespace std;

// function to find the second smallest element
int findSecondSmallest(int arr[], int size)
{
    if (size < 2) {
        cout << "Array should have at least two elements."
             << endl;
        return INT_MAX;
    }

    int smallest = INT_MAX;
    int secondSmallest = INT_MAX;

    for (int i = 0; i < size; ++i) {
        if (arr[i] < smallest) {
            secondSmallest = smallest;
            smallest = arr[i];
        }
        else if (arr[i] < secondSmallest
                 && arr[i] != smallest) {
            secondSmallest = arr[i];
        }
    }

    return secondSmallest;
}

int main()
{
    // Intializing an array
    int arr[] = { 10, 5, 8, 2, 7, 3, 15 };

    // Finding the size of the array
    int size = sizeof(arr) / sizeof(arr[0]);

    // Finding the second smallest element of the array
    int res = findSecondSmallest(arr, size);

    // Printing the second smallest element of the array
    if (res != INT_MAX) {
        cout << "The second smallest element in the array "
                "is: "
             << res << endl;
    }

    return 0;
}

Output
The second smallest element in the array is: 3

Time Complexity: O(N), where N is the number of array elements.
Auxiliary Space: O(1)





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads