Calculating median - javascript

后端 未结 9 824
轮回少年
轮回少年 2021-02-12 09:39

I\'ve been trying to calculate median but still I\'ve got some mathematical issues I guess as I couldn\'t get the correct median value and couldn\'t figure out

9条回答
  •  清酒与你
    2021-02-12 09:57

    Change your median method to this:

    function median(values){
      if(values.length ===0) return 0;
    
      values.sort(function(a,b){
        return a-b;
      });
    
      var half = Math.floor(values.length / 2);
    
      if (values.length % 2)
        return values[half];
    
      return (values[half - 1] + values[half]) / 2.0;
    }
    

    fiddle

提交回复
热议问题