这是一个 C++ 程序,用于查找具有给定复杂性约束的 n 个元素中的第二小。
Begin function SecondSmallest() : /* Arguments to this function are: A pointer array a. Number of elements n */ // 函数体: A variable s1 is declared as to keep track of smallest number. A variable s2 is declared as to keep track of second smallest number. Initialize both s1 and s2 with INT_MAX. Traverse the data array using iteration. If current array element is lesser than current value in s1, then s2 = s1 and s1 = current array element. Else if array element is in between s1 and s2, then s2 = current array element. if(s2==INT_MAX) Print “no second smallest element is present". else Print s2 as second smallest element. End
#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<<"第二小的元素是:"<<s2; } int main() { int n, i; cout<<"输入元素数量: "; cin>>n; int array[n]; for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<< " "<<"element: "; cin>>array[i]; } SecondSmallest(array, n); //调用函数 return 0; }输出结果
输入元素数量: 5 Enter 1 element: 1 Enter 2 element: 2 Enter 3 element: 1 Enter 4 element: 3 Enter 5 element: 4 第二小的元素是:2