This function of this find the median of three values inside an array. I was wondering if there's a more elegant solution to finding the median value between 3 values.

int mid =((p+r)/ 2);
    if(V[p]<V[r]){
      if(V[p]<V[mid]){
        if(V[mid]<V[r])
          swapfunc(V[mid],V[r]);
      }
      else
        swapfunc(V[p],V[r]);
    }
    else{
      if(V[r]<V[mid]){
        if(V[p]<V[mid])
          swapfunc(V[p],V[r]);
        else
          swapfunc(V[mid],V[r]);
      }
    }

I was wondering if there's a more elegant solution to finding the median value between 3 values.

How about using a vector?

size_t len = v2.size();
nth_element( v2.begin(), v2.begin()+len/2,v2.end() );
int median = v2[len/2];

cout << "\nMedian is: " << median << endl;

Much appreciated reply

I think I misstated what I'm trying to achieve in my first post. Say I have 3 variables a,b,c. Instead of finding the minimum or the maximum, I want to find value between them.

Much appreciated reply

I think I misstated what I'm trying to achieve in my first post. Say I have 3 variables a,b,c. Instead of finding the minimum or the maximum, I want to find value between them.

Maybe I'm missing something here but doesn't the following POC demonstrate finding the value between the minimum and maximum?

#include <iostream>
using std::cout;
using std::endl;

#include <algorithm>
#include <vector>
#include <iterator>

int main(void)
{
    int a2[ 3 ] = { 10, 2, 99 };
    std::vector< int > v2( a2, a2 + 3 ); // copy of a2
    size_t len = v2.size();
    nth_element( v2.begin(), v2.begin()+len/2,v2.end() );
    int median = v2[len/2];
    cout << "\nMedian is: " << median << endl;
    return 0;
}

/*
Output:
Median is: 10
*/

Thanks very much for that clarification. And thanks for the solutions.

This question has already been answered. Start a new discussion instead.