Program to find weighted median of a given array | 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 ; Given array arr [ ] ; Given weights W [ ] ; Function Call
function weightedMedian ( arr , W ) { let pr = [ ] ; for ( let index = 0 ; index < arr . length ; index ++ ) pr . push ( [ arr [ index ] , W [ index ] ] ) ; ( pr ) . sort ( function ( a , b ) { return a [ 1 ] - b [ 1 ] ; } ) ; if ( arr . length % 2 != 0 ) { let sums = 0 ; for ( let element = 0 ; element < pr . length ; element ++ ) { sums += pr [ element ] [ 1 ] ; if ( sums > 0.5 ) document . write ( " " + pr [ element ] [ 0 ] + " " ) ; } } else { let sums = 0 ; for ( let element = 0 ; element < pr . length ; element ++ ) { sums += pr [ element ] [ 1 ] ; if ( sums <= 0.5 ) { document . write ( " " + pr [ element ] [ 0 ] + " " ) ; break ; } } sums = 0 ; for ( let index = pr . length - 1 ; index >= 0 ; index -- ) { let element = pr [ index ] [ 0 ] ; let weight = pr [ index ] [ 1 ] ; sums += weight ; if ( sums >= 0.5 ) { document . write ( " " + element ) ; break ; } } } } let arr = [ ] ; arr . push ( 4 ) ; arr . push ( 1 ) ; arr . push ( 3 ) ; arr . push ( 2 ) ; let W = [ ] ; W . push ( 0.25 ) ; W . push ( 0.49 ) ; W . push ( 0.25 ) ; W . push ( 0.01 ) ; weightedMedian ( arr , W ) ;