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.

``````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;``````

Find the min/max. The one that's left is the median.

## All 5 Replies

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

``````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;``````

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.

Find the min/max. The one that's left is the median.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.