Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm ba phần tử nhỏ nhất đầu tiên trong mảng trong C++


Cho mảng n phần tử, tìm phần tử nhỏ nhất thứ nhất, thứ hai, thứ ba. Ví dụ [4,9,18,32,12] → 4, 9, 12.

Duyệt mảng, cập nhật ba biến first, second, third theo điều kiện.

Ví dụ

#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); }

Kết quả

First min = 4 Second min = 9 Third min = 12