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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void weightedMedian ( vector < int > arr , vector < float > W ) { vector < pair < int , float > > pr ; for ( int index = 0 ; index < arr . size ( ) ; index ++ ) pr . push_back ( { arr [ index ] , W [ index ] } ) ; sort ( pr . begin ( ) , pr . end ( ) ) ; if ( arr . size ( ) % 2 != 0 ) { float sums = 0 ; for ( auto element : pr ) { sums += element . second ; if ( sums > 0.5 ) cout << " The ▁ Weighted ▁ Median ▁ is ▁ element ▁ " << element . first << endl ; } } else { float sums = 0 ; for ( auto element : pr ) { sums += element . second ; if ( sums >= 0.5 ) { cout << " Lower ▁ Weighted ▁ Median ▁ is ▁ element ▁ " << element . first << endl ; break ; } } sums = 0 ; for ( int index = pr . size ( ) - 1 ; index >= 0 ; index -- ) { int element = pr [ index ] . first ; float weight = pr [ index ] . second ; sums += weight ; if ( sums >= 0.5 ) { cout << " Upper ▁ Weighted ▁ Median ▁ is ▁ element ▁ " << element ; break ; } } } } int main ( ) { vector < int > arr = { 4 , 1 , 3 , 2 } ; vector < float > W = { 0.25 , 0.49 , 0.25 , 0.01 } ; weightedMedian ( arr , W ) ; }