Search code examples
c++searchvectorminimum

C++ Variable not properly receiving new value from vector?


I'm trying to write a program that creates and fills a vector with int values, then searches through it and returns the minimum value, recursively. I have the code written out and building, but it returns a weirdly large value for minimum every time- I have a feeling it's not properly assigning the smallest value to int minimum, but I'm not sure. Any thoughts?

#include <iostream>
#include <conio.h>
#include <vector>

using namespace std;

int vectorSize;
int minimum;
int result = -1;
int start;
int ending;
int answer;
int test;

int recursiveMinimum(vector<int>, int, int);

void main() {
    cout << "How many values do you want your vector to be? ";
    cin >> vectorSize;
    cout << endl;

    vector<int> searchVector(vectorSize);

    start = 0;
    ending = searchVector.size() - 1;

    for (int i = 0; i < vectorSize; i++) {
        cout << "Enter value for position " << i << " " << endl;
        cin >> searchVector[i];
    }

    for (int x = 0; x < vectorSize; x++) {
        cout << searchVector[x] << " ";
    }

    int answer = recursiveMinimum(searchVector, start, ending);
    cout << "The smallest value in the vector is: " << answer;

    _getch();
}

int recursiveMinimum(vector<int> searchVector, int start, int end) {
    if (start < end) {
        if (searchVector[start] < minimum) {
            minimum = searchVector[start]; //this part seems to not work
        }

        start++;
        recursiveMinimum(searchVector, start, end);
    }
    else {
        return minimum;
    }
}
`

Solution

  • Your minimum variable is not initialised, which leads to undefined behaviour. It should be set to the first value in the vector:

    minimum = searchVector[0];
    int answer = recursiveMinimum(searchVector, start, ending);
    

    Additionally, ending is off by one, which makes it pick 6 as the smallest value out of [6, 9, 8, 4].

    So, ultimately, your code should look like this:

    minimum = searchVector[0];
    int answer = recursiveMinimum(searchVector, start, ending + 1); // note the + 1
    

    While irrelevant to the question, I advise you to use a tail call in recursiveMinimum, as explained here:

    start++;
    return recursiveMinimum(searchVector, start, end);