# Thread: Median and Mode of an Array

1. ## Median and Mode of an Array

I am trying to write a program that will find the meadian and mode of the values in an array.

This is the code I have so far for Median:

Code:
```void median (double array[], int numItems)
{
int i, j;
double hold;

for (i = 0; i <(numItems - 1); i++)
{
for (j = i+1; j < numItems; j++)
{
if (array [j] < array [i])
{
hold = array[i];
array[i] = array[j];
array[j] = hold;
}
}
}

if (numItems % 2 == 0)
{
printf ("\nThe median is %.1lf\n", ((array[numItems/ 2] + array[numItems/2 + 1]) / 2));
}
else
{
printf ("\nThe median is %.1lf\n", array[(numItems/ 2)]);
}
}```
And for the Mode I have:

Code:
```void mode (double array [], int numItems)
{
int largestcount, i, j;
int count [1500] = {0};
double mode;

for (i = 0; i < numItems; i++)
{
for (j = 0; j < numItems; j++)
{
if (i != j)
{
if (array[i] == array[j])
{
count[i];
}
}
}
}

mode = array[0];
largestcount = count[0];

for (i = 0; i <numItems; i++)
{
if (count[i] > largestcount)
largestcount = count[i];
mode = array[i];
}

printf ("\nThe mode is %i\n", mode);
}```
I'm having a little trouble trying to figure this one out to.

Any info on this would be great.

2. Have you learnt about quicksort? As an advanced exercise for median, you could use the nth element algorithm that involves doing quicksort-style partitioning, but only performing the recursion on the partition that contains the median element. This would give you the median in linear time in the average case.

For an array of doubles, it may make more sense to consider modal class than mode due to floating point inaccuracy.

3. Originally Posted by laserlight
For an array of doubles, it may make more sense to consider modal class than mode due to floating point inaccuracy.
True, but it does give the additional need to specify an appropriate set of intervals to subdivide the range of data. That requires additional information (where the data came from, what the computed statistics will be used for, etc etc)

4. Have you learnt about quicksort?
I have to do my own sorting.

If anybody knows how I can fix the existing code I have that would be great