下面是我编写的用于在 C++ 中查找未排序数组的最小元素的代码。
我应该如何编辑我的递归函数以找到数组中第二甚至第三小的元素?
我知道还有其他方法(我已经搜索过),但是我想知道如何使用像这样的递归函数来做到这一点,它只适用于最小数量。
int min(vector<int> &array, int &min, int &next_min, int left,int right)
{
int a;
int b;
if(left == right) {
return array[left];
} else {
int mid= (right+left)/2;
a = min(array,left,mid);
b = min(array,mid+1,right);
if (a<b)
return b;
else
return a;
}
}
提前谢谢了
这是我寻找第二小的尝试:
#include<iostream>
#include<vector>
#include <cstdlib>
using namespace std;
int counter=0;
void minf(vector<int> &array,int left,int right,int &min, int &next_min);
int main()
{
int next_min;
cout << "Enter integers one line at a time. (Enter -999 to terminate)" << endl;
vector<int> array; //
int input;
while(true){
cin >> input;
if(input == -999) //check for termination condition
break;
array.push_back(input);
}
int imin;
int imax;
cout<<"Enter imin, then imax"<<endl;
cin>>imin;
cin>>imax;
cout<<"Min number is " << next_min <<endl;
cin.get();
system("pause");
return 0;
}
void minf(vector<int> &array,int left,int right,int &min, int &next_min)
{
int a;
int b;
int c;
int d;
if(left == right) {
min = array[left];
next_min = 2147483647;
} else {
int mid= (right+left)/2;
minf(array,left,mid,a,b);
minf(array,mid+1,right,c,d);
if (a < b && a < c && a < d) {
min = a;
if (b<c && b <d)
next_min = b;
else if (c < b && c < d)
next_min = c;
else
next_min = d;
}
if (b < a && b < c && b < d){
min = b;
if (a<c && a <d)
next_min = a;
else if (c < b && c < d)
next_min = c;
else
next_min = d;
}
if (c < a && c < b && c < d) {
min = c;
if (b<a && b<d)
next_min = b;
else if (a < b && a < d)
next_min = a;
else
next_min = d;
}
if (d < a && d < c && d < b){
min = d;
if (a<c && a <b)
next_min = a;
else if (c < b && c < a)
next_min = c;
else
next_min = b;
}
}
}