สมมติว่าเรามีอาร์เรย์ขององค์ประกอบ 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);
} ผลลัพธ์
First smallest = 4 Second smallest = 9