I'm writing a function that is supposed to recursively find the smallest positive number in a give vector of ints.
Right now my code looks like this:
#include <vector>
using namespace std;
int rec_min_pos(const vector<int> & nums, int size) {
if (size < 1) {
return -1;
} else {
int min = rec_min_pos(nums, size - 1);
if(min < 0){
if(nums[size - 1] <= 0){
return -1;
}else{
return nums[size-1];
}
}else {
if (min < nums[size - 1]) {
return min;
} else {
return nums[size - 1];
}
}
}
}
int main(){
vector<int> nums = {2, -3, 6, -21, 10, -80, 8};
cout << rec_min_post(nums, nums.size());
}
If I run this, I get 8
, which is presumably because the next element is negative.
The previous version:
#include <vector>
using namespace std;
int rec_min_pos(const vector<int> & nums, int size) {
if (size < 1) {
return -1;
} else {
int min = rec_min_pos(nums, size - 1);
if (min < nums[size - 1]) {
return min;
} else {
return nums[size - 1];
}
}
}
int main(){
vector<int> nums = {2, -3, 6, -21, 10, -80, 8};
cout << rec_min_post(nums, nums.size());
}
I would get -80
which is in fact the smallest value, but I need the smallest positive value.
What can I do to get the smallest positive value from the integer vector?
See Question&Answers more detail:os