Cho mảng n phần tử. Tìm phần tử nhỏ nhất (first smallest) và nhỏ thứ hai (second smallest). Phần tử nhỏ nhất là min của mảng, nhỏ thứ hai là min nhưng lớn hơn nhỏ nhất.
Duyệt qua từng phần tử, kiểm tra và cập nhật điều kiện cho phần tử nhỏ nhất và nhỏ thứ hai.
Ví dụ mã nguồn
#include <iostream>
using namespace std;
int getTwoSmallest(int arr[], int n) {
int first = INT_MAX, sec = INT_MAX;
for (int i = 0; i < n; i++) {
if (arr[i] < first) {
sec = first;
first = arr[i];
} else if (arr[i] < sec) {
sec = arr[i];
}
}
cout << "First smallest = " << first << endl;
cout << "Second smallest = " << sec << endl;
}
int main() {
int array[] = {4, 9, 18, 32, 12};
int n = sizeof(array) / sizeof(array[0]);
getTwoSmallest(array, n);
}
Kết quả đầu ra
First smallest = 4 Second smallest = 9