Finding Median of an Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
case 'M':
        case 'm':
        int j;
        int size;
        double average, median;
        if(i == 0)
             {
               cout << "ERROR" << endl;
                break;
               }
             j = size / 2.0;
            if (size % 2)
            {
                median = (aArray[j] + aArray[j + 1]) / 2.0;
                cout << "The median is: " << average << endl;
            }
            else
            {
                median = aArray[j + 0] / 1.0;
                cout << "The median is: " << median << endl;
            }
            break;



I have this case where I am trying to find the median of an array but it is not working can someone tell me why. If you need my entire code let me know.
Last edited on
size % 2 is true when size is odd. When there are an odd number of elements in a sequence, the median is one element of the sequence, not the average of two of elements.

When the number of elements in a (sorted) sequence is even, the median is the average of the elements indexed by size/2 and size/2-1.

I am really confused. This is the last case I need to complete in my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
case 'M':
        case 'm':
        int j;
        int num;

        if(i == 0)
             {
               cout << "ERROR" << endl;
                break;
               }
               if(num % 2 != 0){//
              int j = ((num+1)/2)-1;
                    cout << "The median is " << aArray[j] << endl;
                }
                else{// then it's even! :)
                    cout << "The median is "<< aArray[(num/2)-1] << " and " << aArray[num/2] << endl;
                }
            }
Will this work
Will this work

It would appear so, although line 12 looks unnecessarily complicated.

int j = num/2; will give the same result given the way integer division works.

Median index of five elements:
         ___
| 0 | 1 | 2 | 3 | 4 |

5/2  =>  2

(5+1)/2 - 1  =>  6/2 - 1  =>  3 - 1  =>  2


It hasn't worked. For this program we are inputting numbers and storing them into the array. I've inputted 2,2,3,5,6. The median should be 3 but it says that it is 0 and 2.
I have been presuming there was more code in there that you didn't post here. In the latest code you've posted here, num is uninitialized and contains no specific value. It does not represent the number of elements in the array.
I sent you a PM of my entire code.
In the PM, you suffer from the same problem you do in the code you posted here. num does not represent the number of elements in the array. It has some random value. The number of elements in the array seem to be represented by a generically named variable i.

Replacing int num; with int num=i; would probably do the trick for you.
Topic archived. No new replies allowed.