Sort an array according to absolute difference with given value | C ++ program to sort an array according absolute difference with x . ; Function to sort an array according absolute difference with x . ; Store values in a map with the difference with X as key ; Update the values of array ; Function to print the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrange ( int arr [ ] , int n , int x ) { multimap < int , int > m ; multimap < int , int > :: iterator it ; for ( int i = 0 ; i < n ; i ++ ) m . insert ( make_pair ( abs ( x - arr [ i ] ) , arr [ i ] ) ) ; int i = 0 ; for ( it = m . begin ( ) ; it != m . end ( ) ; it ++ ) arr [ i ++ ] = ( * it ) . second ; } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 10 , 5 , 3 , 9 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 7 ; rearrange ( arr , n , x ) ; printArray ( arr , n ) ; return 0 ; }