Median calculation in ActionScript 3

Posted by Gabor Kako on Stack Overflow See other posts from Stack Overflow or by Gabor Kako
Published on 2012-04-03T05:03:14Z Indexed on 2012/04/03 5:29 UTC
Read the original article Hit count: 240

Filed under:

I have a number array and I'd like to calculate the median. When the array is odd, the calculation is OK, when it's even strange number comes up.

private var numbers:String = "2,5,3,4,6,1";
private var array:Array = numbers.split(",");

private function getMedian(array:Array):Number {
 var sortnums:Array = array.sort(Array.NUMERIC);
 var length:Number = sortnums.length;
 var mid1:Number; var mid2:Number; var median:Number;

 if(length % 2 == 0){
     mid1 = length / 2; trace("mid1: "+mid1);
 mid2= ((length - 1) / 2)-0.5; trace("mid2: "+mid2);
 trace ("mid1: "+sortnums[mid1]+", mid2: "+sortnums[mid2]);
 median = (sortnums[mid1] + sortnums[mid2]) / 2;
 }else{
 mid1 = (length / 2)-0.5
 median = sortnums[mid1]
 }
 trace (median);
 return median;
}

The result is 21.5, but should be 3.5

mid1 and mid2 are a position in the array.

Could somebody help?

© Stack Overflow or respective owner

Related posts about actionscript-3