Program to find weighted median of a given array | C # program for the above approach ; Function to calculate weighted median ; Store pr of arr [ i ] and W [ i ] ; Sort the list of pr w . r . t . to their arr [ ] values ; If N is odd ; Traverse the set pr from left to right ; Update sums ; If sum becomes > 0.5 ; If N is even ; For lower median traverse the set pr from left ; Update sums ; When sum >= 0.5 ; For upper median traverse the set pr from right ; Update sums ; When sum >= 0.5 ; Driver code ; Given array arr [ ] ; Given weights W [ ] ; Function Call
using System ; using System . Collections . Generic ; class GFG { static void weightedMedian ( int [ ] arr , float [ ] W ) { List < Tuple < int , float > > pr = new List < Tuple < int , float > > ( ) ; for ( int index = 0 ; index < arr . Length ; index ++ ) pr . Add ( new Tuple < int , float > ( arr [ index ] , W [ index ] ) ) ; pr . Sort ( ) ; if ( arr . Length % 2 != 0 ) { float sums = 0 ; foreach ( Tuple < int , float > element in pr ) { sums += element . Item2 ; if ( sums > 0.5 ) Console . WriteLine ( " The ▁ Weighted ▁ Median ▁ " + " is ▁ element ▁ " + element . Item1 ) ; } } else { float sums = 0 ; foreach ( Tuple < int , float > element in pr ) { sums += element . Item2 ; if ( sums >= 0.5 ) { Console . WriteLine ( " Lower ▁ Weighted ▁ Median ▁ " + " is ▁ element ▁ " + element . Item1 ) ; break ; } } sums = 0 ; for ( int index = pr . Count - 1 ; index >= 0 ; index -- ) { int element = pr [ index ] . Item1 ; float weight = pr [ index ] . Item2 ; sums += weight ; if ( sums >= 0.5 ) { Console . Write ( " Upper ▁ Weighted ▁ Median ▁ " + " is ▁ element ▁ " + element ) ; break ; } } } } static void Main ( ) { int [ ] arr = { 4 , 1 , 3 , 2 } ; float [ ] W = { 0.25f , 0.49f , 0.25f , 0.01f } ; weightedMedian ( arr , W ) ; } }