RIf Rahman
RIf Rahman

Reputation: 5

Need help searching for minimum value in a vector that is filled with users input

double find_min(sample &s){
    double i = 0;
    double min;
    for (i; i < s.get_data().size() - 1; i++){
        if (s.get_data().at(i) < s.get_data().at(i + 1)){
            min = s.get_data().at(i);
        }
        else{
            min = s.get_data().at(i + 1);
        }
    }
    return min;
}

Im trying to find the minimum value for a vector that is filled with a users input. When there is a small number, x, and all other numbers after it are bigger than x; the function works fine.

However when a number smaller than x, lets call it y, appears after x the function returns y.

Example 1: vector values of [23,44,55,1,66,77] -> function will correctly return 1;

Example 2: vector values of [23,44,55,1,3,44] -> function returns 3?

Upvotes: 0

Views: 48

Answers (3)

nishparadox
nishparadox

Reputation: 770

Just assume that your first element is the minimum and start to compare from the second element. If another element is lesser than the previously set element(initially first element), then set this element as new element.

double find_min(sample &s)
{
  double min  = s.get_data().at(0);

  for (int i=1; i < s.get_data().size() - 1; i++)
  {
    if (s.get_data().at(i) < min)
    {
      min = s.get_data().at(i);
    }
  }
  return min;
}

and by the way, you can overload the index operator '[]' to set/get elements just like an array

Upvotes: 0

Petro Kostyuk
Petro Kostyuk

Reputation: 153

As Kenny said, you have to compare it against min. It will look like this:

double find_min(sample &s){
  double i = 0;
  int min_index = 0;
  for (i; i < s.get_data().size() - 1; i++){
    if (s.get_data().at(i) < s.get_data().at(min_index)){
      min_index = i;
    }
  }
  return s.get_data().at(min_index);
}

Upvotes: 0

Kenny Ostrom
Kenny Ostrom

Reputation: 5871

You need to compare the number against min. You are just looking for the last number which is smaller than the following number, and 3<44.

Upvotes: 1

Related Questions