Median formula problem

hello , i want a formula for calculating the median of an even array
what if the array is made of random numbers ???
for example it is not {1,2,3,4}
it is {1,5,8,10}??
Then the median of that array is the mean of 5 and 8. (5+8)/2 = 6½
You sort them first and take the item at position arr[n/2] if n is odd,
otherwise, 0.5 * (arr[n/2] + arr[n/2-1]).
but now the median value isnt in the array
and here is the code i wrote
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

double mid(int arr[],int size)
 {
int i,t,f;
double even,odd;
t=(size/2);
f=(size/2)-1;

even=(((arr[t]+arr[f]))/2);
odd=arr[t];
for(i=0;i<size;i++)
{
if(size%2==0)

return even;
return odd;
}

and the median is not always within the array , how to fix that ??
Last edited on
The median value need not be in the array. Re-read the wiki page carefully and then recode.

Also, make sure you work the code for edge cases like size==0, size==1, and if you want to use an int, size<0.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;



int main() {

    int iArray[] = {2,10,5,1,55,7,48,103,22,6,3,99,45,99}; // LoL, as random as I can think of em.


    vector<int> mArray(iArray,iArray+14); // Remember to set this number to match the number of items in your int array
    vector<int>::iterator it;

    sort(mArray.begin(),mArray.end());

// Find the median.
    float median,middle,middleh;
    float middlel;
    vector<int>::iterator z;
    switch(mArray.size()%2) {
        case(0): // even
            z = mArray.begin();
            middlel = mArray.size()/2;
            z += middlel;
            middleh = (*z+*(--z))/2;
            cout << "Median is: " << middleh << endl;
        break;
        case(1): // odd
            z = mArray.begin();
            middle = mArray.size()/2;
            cout << "Median is : " << *(z+=middle) << endl;
        break;
    }


    // display the sorted array.
    for(it=mArray.begin();it!=mArray.end();it++) {
        cout << *it << " ";
    }


    cout << endl;




    return 0;
}
Last edited on
Since we're providing full solutions, you can make that a lot simpler:

1
2
3
4
int a[] = {2, 10, 5, 1, 55, 7, 48, 103, 22, 6, 3, 99, 45, 99};
int size = sizeof(a)/sizeof(int);
std::sort(&a[0], &a[size]);
double median = size % 2 ? a[size / 2] : (a[size / 2 - 1] + a[size / 2]) / 2;
Last edited on
ooo, very nice. Obviously I need to start incorporating more ternary operators.
Just for the notice, although his code is nice, the ternary operator just overcomplicates things in a lot of cases, so you may not always want to use it.

1
2
#include <cstdio>
unsigned _(unsigned ___,unsigned __=0.f){__<___?printf("%d\n",__),_(___,__+___/___):__-__;}main(){_(011);for(;,;);}

Couldn't resist posting that. :P
Last edited on
Topic archived. No new replies allowed.