user287474 - 1 year ago 63

C Question

How would you find the median of an array full of frequencies of the number?

To be more accurate, I have this array where I have the number of instances of a integer:

`array[0] = 0`

array[1] = 15

array[2] = 8

array[3] = 9

...

And so on.

This is my code for trying to calculate the median but I'm stuck:

`int array[128];`

int total = 86 /** previously added up in the code, can arbitrarily change **/;

int index = total/2;

int median = 0;

for(i = 0 ; i < size ; i++){

total += array[i];

if(total >= index){

median = i;

break;

}

}

//median will then contain the median

Right now, all it returns is 0.

Can anyone please tell me what i'm doing wrong or point me in the right direction?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You are supposed to set your running total to zero before the loop!

```
int total = 86
```

While it's true that you'll need the 86 for the halfway point (`index`

in your code), you really need this value to be 0 before the loop.

I recommend using a completely different variable to maintain the running total from the variable you store the 86 in.

Also, what is the `array`

variable for? I assume you mean to use `graph`

in your loop.