Compute Median of Values Stored In Vector - C++?

后端 未结 6 654
故里飘歌
故里飘歌 2020-11-29 03:40

I\'m a programming student, and for a project I\'m working on, on of the things I have to do is compute the median value of a vector of int values. I\'m to do this using onl

6条回答
  •  暖寄归人
    2020-11-29 03:56

    The accepted answer uses std::sort which does more work than we need it to. The answers that use std::nth_element don't handle the even size case correctly.


    We can do a little better than just using std::sort. We don't need to sort the vector completely in order to find the median. We can use std::nth_element to find the middle element. Since the median of a vector with an even number of elements is the average of the middle two, we need to do a little more work to find the other middle element in that case. std::nth_element ensures that all elements preceding the middle are less than the middle. It doesn't guarantee their order beyond that so we need to use std::max_element to find the largest element preceding the middle element.

    int CalcMHWScore(std::vector hWScores) {
      assert(!hWScores.empty());
      const auto middleItr = hWScores.begin() + hWScores.size() / 2;
      std::nth_element(hWScores.begin(), middleItr, hWScores.end());
      if (hWScores.size() % 2 == 0) {
        const auto leftMiddleItr = std::max_element(hWScores.begin(), middleItr);
        return (*leftMiddleItr + *middleItr) / 2;
      } else {
        return *middleItr;
      }
    }
    

    You might want to consider returning a double because the median may be a fraction when the vector has an even size.

提交回复
热议问题