Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ หาตัวเลขอันดับสองที่น้อยที่สุดของ n องค์ประกอบ ภายใต้เงื่อนไข Complexity


นี่คือโปรแกรม C++ สำหรับหาตัวเลขอันดับสองที่น้อยที่สุด (Second Smallest) ของ n องค์ประกอบ ภายใต้เงื่อนไข Complexity ที่กำหนด

อัลกอริทึม

เริ่มต้น    ฟังก์ชัน SecondSmallest() :       /* อาร์กิวเมนต์ของฟังก์ชันนี้คือ:          อาร์เรย์พอยน์เตอร์ a          จำนวนองค์ประกอบ n       */    // ส่วนตัวของฟังก์ชัน:       ตัวแปร s1 ประกาศไว้เพื่อติดตามตัวเลขน้อยที่สุด       ตัวแปร s2 ประกาศไว้เพื่อติดตามตัวเลขอันดับสองที่น้อยที่สุด       เริ่มต้น s1 และ s2 ด้วย INT_MAX       ท่องอาร์เรย์ข้อมูลโดยใช้การวนซ้ำ (Iteration)       ถ้าองค์ประกอบอาร์เรย์ปัจจุบันน้อยกว่าค่าปัจจุบันใน s1 แล้ว s2 = s1 และ s1 =          องค์ประกอบอาร์เรย์ปัจจุบัน          มิฉะนั้น ถ้าองค์ประกอบอาร์เรย์อยู่ระหว่าง s1 และ s2             แล้ว s2 = องค์ประกอบอาร์เรย์ปัจจุบัน          ถ้า(s2==INT_MAX)             พิมพ์ “no second smallest element is present”          มิฉะนั้น       พิมพ์ s2 เป็นตัวเลขอันดับสองที่น้อยที่สุด จบ

ตัวอย่างโค้ด

#include<iostream> #include <climits> //สำหรับ INT_MAX using namespace std; int SecondSmallest(int *a, int n) {    int s1, s2, i,t;    //เริ่มต้น s1 และ s2    s1 =INT_MAX;    s2=INT_MAX;    for(i = 0; i < n; i++) {       //ถ้าองค์ประกอบปัจจุบันน้อยกว่า s1       if(s1 > a[i]) {          //อัปเดต s1 และ s2          s2 = s1;          s1 = a[i];       }       //ถ้า a[i] อยู่ระหว่าง s1 และ s2       else if(s2 > a[i] && a[i]!=s1) {          //อัปเดตแค่ s2          s2 = a[i];       }    }    if(s2==INT_MAX)       cout<<"no second smallest element is present";    else       cout<<"Second smallest element is:"<<s2; } int main() {    int n, i;    cout<<"Enter the number of elements: ";    cin>>n;    int array[n];    for(i = 0; i < n; i++) {       cout<<"Enter "<<i+1<< " "<<"element: ";       cin>>array[i];    }    SecondSmallest(array, n); //เรียกฟังก์ชัน    return 0; }

ผลลัพธ์

Enter the number of elements: 5 Enter 1 element: 1 Enter 2 element: 2 Enter 3 element: 1 Enter 4 element: 3 Enter 5 element: 4 Second smallest element is:2