Finding the median value of an array?

后端 未结 9 1328
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 14:58

I was wondering if it was possible to find the median value of an array? For example, suppose I have an array of size nine. Would it possible to find the middle slot of this

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 15:23

    The Java answer above only works if there are is an odd ammount of numbers here is the answer I got to the solution:

    if (yourArray.length % 2 == 0){
    
         //this is for if your array has an even ammount of numbers
         double middleNumOne = yourArray[yourArray.length / 2 - 0.5]
         double middleNumTwo = yourArray[yourArray.length / 2 + 0.5]
         double median = (middleNumOne + middleNumTwo) / 2;
         System.out.print(median);
    
    }else{
    
         //this is for if your array has an odd ammount of numbers
         System.out.print(yourArray[yourArray.length/2];);
    }
    

    And note that this is a proof of concept and off the fly. If you think that you can make it more compact or less intensive, go right ahead. Please don't criticize it.

提交回复
热议问题