Skip to content

Commit

Permalink
Add median() function to mm.c
Browse files Browse the repository at this point in the history
Resolve smuos#3
  • Loading branch information
DylanYoung committed Sep 24, 2014
1 parent 826e347 commit 7cfcf60
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions mm.c
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,21 @@ double mean(const void *a, int length, int size){
return (double) sum / length; // Return the average
}

/*/ Takes a pointer to a sorted array of ints and the
* length of the array and returns a double,the median
* value, or the average of the two median values
*/
double median(const int *a, int length){
double result;
if (length % 2 == 0)
result = (*((int*) (a + length/2) - 1) + *((int*) (a + length/2)) ) / 2;
else
result = *((int*) (a + (length+1)/2 - 1));
return result;
}



int main(int argc, char *argv[]) {

int i, length, *pt;
Expand Down Expand Up @@ -68,9 +83,16 @@ int main(int argc, char *argv[]) {

// Calculate the mean
double m = mean(pt, length, sizeof(int));

// Calculate the median
double mm = median(pt, length);

// Print the mean:
fprintf(stdout, "%s: The mean is %f \n", argv[0], m);

// Print the median:
fprintf(stdout, "%s: The median is %f \n", argv[0], mm);

// Print out sorted numbers
fprintf(stdout, "%s: Sorted output is: \n", argv[0]);
for (i=0; i<length; i++) {
Expand Down

0 comments on commit 7cfcf60

Please sign in to comment.