Thread: Help with finding median with arrays.

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    11

    Help with finding median with arrays.

    I've got a slight problem with the final part of a program I've been working on. It uses one-dimensional arrays, sorts the results in order, processes and prints the average of the numbers in the array. The final part of the program is to find the median of the numbers in the array.

    /* Function prototype: */

    double med_dbl_arr(double array[], int n);

    /* Function Call */

    median=med_dbl_arr(sorted_list, n);

    /* Passing the sorted list and number of elements in array */

    /* Function Definition */

    double med_dbl_arr(double array[], int n)

    At this point, the sucker gets a little hazy. I'm lost at this point. Any ideas?

    Colin

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    With an odd number of values, the median of the values in the array is the one in the very middle, or len / 2. When there is an even number of values, the median is the sum of the two middle numbers divided by 2.
    Example:

    4 9 5 6 0
    The median is 5

    4 9 6 5 3 1
    The median is 5.5, ( 6 + 5 ) / 2 = 5.5

    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    11

    I know how to do it mathematically, but the code is eluding me...

    I have a good grasp of the mathematical concepts of finding a median, but I've been working for four days on this little bit of code. Nothing I do seems to work properly...

    Colin

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    What's so hard about it?
    Code:
    mid = len / 2;
    if ( len & 1 )
      printf ( "%d\n", array[mid] );
    else
      printf ( "%d\n", ( array[mid] + array[mid - 1] ) / 2 );
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 04-26-2009, 02:46 PM
  2. Finding the sum of even numbers using arrays
    By Fox101 in forum C Programming
    Replies: 7
    Last Post: 12-03-2007, 02:20 PM
  3. Finding Mode Median and Mean
    By Ginny Morgan in forum C Programming
    Replies: 3
    Last Post: 05-08-2003, 03:09 PM
  4. Computing Mean, Median and Mode Using Arrays
    By Rodneo in forum C++ Programming
    Replies: 0
    Last Post: 05-29-2002, 11:40 PM
  5. mean and median using arrays, help!!
    By brandondere in forum C Programming
    Replies: 4
    Last Post: 10-15-2001, 05:54 PM