Thread: Median

  1. #1
    Registered User
    Join Date
    Sep 2006
    Kansas City


    I have a simple code which gets a median form a file of intigers.
    Here is part of it:
           int total = 0 ;
           int number = 0;
           int middle;
           for (int i  ; intiger_stream >> number ; i ++ )
               total ++ ;
            middle =  (total + 1)/2 ;
            cout << "Median : " << middle  << endl;
    It works fine, but I heard that a better way of finding a median is by passing through the intigers in the file twice, first getting the total intigers and on the second pass getting an intiger in the middle (the median).

    I can't figureout how to find the median via that second method.

    Could someone give me a hint.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Your code does not compute the median. Instead it prints out (n+1)/2 where n is the number of values input.

    Try placing the values "27 23 29" into your file. Your code will probably report that the median is 2. In reality, the median of 27, 23, and 29 is 27. I would suggest that reporting a value of 2 is a sign that your algorithm isn't quite correct.

    Given a set of values, the median is a value such that no more than half of the complete set is less than the median and no more than half of the set is greater. For an odd number of values (as in my example) the median can be found by sorting the values - the median is the value in the middle of the sorted sequence. For an even number of values the median is found by sorting the values, and then taking the average of two values on either side of the middle (eg set 10 23 17 11 would be sorted to 10 11 17 23 and the median will be computed as (11+17)/2 = 14)

    There is also an issue that the shenanigans with i in the loop yield undefined behaviour (as i is not initialised, and then it is repeatedly incremented), although in practice that probably won't change much because you do nothing with i (and a fair few compilers will optimise that variable out of existence).
    Last edited by grumpy; 10-21-2006 at 02:13 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Median filter help
    By JTEK24 in forum Tech Board
    Replies: 10
    Last Post: 07-16-2009, 06:05 PM
  2. moving median function
    By supermeew in forum C Programming
    Replies: 0
    Last Post: 05-04-2006, 02:37 PM
  3. Computing Mean, Median and Mode Using Arrays
    By Rodneo in forum C++ Programming
    Replies: 0
    Last Post: 05-29-2002, 11:40 PM
  4. median
    By frank in forum C++ Programming
    Replies: 4
    Last Post: 10-28-2001, 03:32 PM
  5. mean and median using arrays, help!!
    By brandondere in forum C Programming
    Replies: 4
    Last Post: 10-15-2001, 05:54 PM