Thread: Median

  1. #1
    Internet Superhero
    Join Date
    Sep 2006
    Location
    Denmark
    Posts
    964

    Median

    Shouldn't the following code return the Median of the "Data" array?

    Code:
    int Median(int Data[], int Length)
    {
    	int i = 0, j = 0, Temp = 0;
    	
    	for(i; i < Length; i++)
    	{
    			for(j = 0; j < (Length - 1); j++)
    			{
    						if(Data[j] > Data[j+1])
    						{
    										Temp = Data[j+1];
    										Data[j+1] = Data[j];
    										Data[j] = Temp;
    						}
    			}
    	}
    	
    	i = (Length / 2);
    	
    	if((Length % 2) == true)
    	{
    			return(Data[i]);
    	}
    	
    	else
    	{
    			if(Data[i] == Data[i+1])
    			{
    						return(Data[i]);
    			}
    			
    			else
    			{
    						return((Data[i] + Data[i-1]) / 2);
    			}
    	}
    }
    If the Data array contains 4 - 4 - 5 - 6 -6 the function returns 4 as the median, rather than 5, why is that? What have i done wrong?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    It returned 5 when I ran it. Maybe your main() is different.

  3. #3
    cout << "Bye World!";
    Join Date
    Jun 2006
    Posts
    40
    yeah check ur main(). im getting 5 as well. it should look something like this:
    Code:
    int main(){
    	int data[5] = {4,4,5,6,6};
    	cout << Median(data, 5) << endl;
    	return 0;
    }

  4. #4
    Internet Superhero
    Join Date
    Sep 2006
    Location
    Denmark
    Posts
    964
    I just realized.

    I was reading the data into the array from a file, with a number on each line. The last line in the file was empty though, so i guess the length of the file got screwed up, and the length passed to the function was wrong. Stupid mistake, sorry about that.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Make sure you aren't using eof() to control your loop, as that can screw those things up as well.

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, 04: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