Program to find weighted median of a given array | Java 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
import java . util . * ; class GFG { static class Pair implements Comparable < Pair > { int first ; double second ; Pair ( int f , double s ) { first = f ; second = s ; } @ Override public int compareTo ( Pair o ) { if ( this . second > o . second ) return 1 ; else if ( this . second == o . second ) return 0 ; return - 1 ; } } static void weightedMedian ( Vector < Integer > arr , Vector < Double > W ) { Vector < Pair > pr = new Vector < > ( ) ; for ( int index = 0 ; index < arr . size ( ) ; index ++ ) pr . add ( new Pair ( arr . get ( index ) , W . get ( index ) ) ) ; Collections . sort ( pr ) ; if ( arr . size ( ) % 2 != 0 ) { float sums = 0 ; for ( Pair element : pr ) { sums += element . second ; if ( sums > 0.5 ) System . out . print ( " The ▁ Weighted ▁ Median ▁ is ▁ element ▁ " + element . first + "NEW_LINE"); } } else { double sums = 0 ; for ( Pair element : pr ) { sums += element . second ; if ( sums <= 0.5 ) { System . out . print ( " Lower ▁ Weighted ▁ Median ▁ is ▁ element ▁ " + element . first + "NEW_LINE"); break ; } } sums = 0 ; for ( int index = pr . size ( ) - 1 ; index >= 0 ; index -- ) { int element = pr . get ( index ) . first ; double weight = pr . get ( index ) . second ; sums += weight ; if ( sums >= 0.5 ) { System . out . print ( " Upper ▁ Weighted ▁ Median ▁ is ▁ element ▁ " + element ) ; break ; } } } } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < > ( ) ; arr . add ( 4 ) ; arr . add ( 1 ) ; arr . add ( 3 ) ; arr . add ( 2 ) ; Vector < Double > W = new Vector < > ( ) ; W . add ( 0.25 ) ; W . add ( 0.49 ) ; W . add ( 0.25 ) ; W . add ( 0.01 ) ; weightedMedian ( arr , W ) ; } }