 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the first, second and third minimum elements in an array in C++
Suppose we have an array of n elements. We have to find the first, second and the third minimum elements in the array. First minimum is the minimum of the array, second min is minimum but larger than the first one, and similarly the third min is minimum but greater than second min.
Scan through each element, then check the element, and relate the condition for first, second and third min elements conditions to solve this problem.
Example
#include<iostream> using namespace std; int getThreeMins(int arr[], int n) {    int first = INT_MAX, sec = INT_MAX, third = INT_MAX;       for (int i = 0; i < n; i++) {          if (arr[i] < first) {             third = sec;             sec = first;             first = arr[i];          } else if (arr[i] < sec) {             third = sec;             sec = arr[i];          } else if (arr[i] < third)             third = arr[i];    }    cout << "First min = " << first << endl;    cout << "Second min = " << sec << endl;    cout << "Third min = " << third << endl; } int main() {    int array[] = {4, 9, 18, 32, 12};    int n = sizeof(array) / sizeof(array[0]);    getThreeMins(array, n); }  Output
First min = 4 Second min = 9 Third min = 12
Advertisements
 