How to calculate the median of an array?

后端 未结 14 1738
北海茫月
北海茫月 2020-12-05 06:10

I\'m trying to calculate the total, mean and median of an array thats populated by input received by a textfield. I\'ve managed to work out the total and the mean, I just ca

14条回答
  •  情书的邮戳
    2020-12-05 06:55

    Arrays.sort(numArray);
    int middle = ((numArray.length) / 2);
    if(numArray.length % 2 == 0){
     int medianA = numArray[middle];
     int medianB = numArray[middle-1];
     median = (medianA + medianB) / 2;
    } else{
     median = numArray[middle + 1];
    }
    

    EDIT: I initially had medianB setting to middle+1 in the even length arrays, this was wrong due to arrays starting count at 0. I have updated it to use middle-1 which is correct and should work properly for an array with an even length.

提交回复
热议问题