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
using System ; using System . Collections . Generic ; public class GFG { static void rearrange ( int [ ] arr , int n , int x ) { SortedDictionary < int , List < int > > m = new SortedDictionary < int , List < int > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int diff = Math . Abs ( x - arr [ i ] ) ; if ( m . ContainsKey ( diff ) ) { List < int > al = m ; al . Add ( arr [ i ] ) ; m = al ; } else { List < int > al = new List < int > ( ) ; al . Add ( arr [ i ] ) ; m . Add ( diff , al ) ; } } int index = 0 ; foreach ( int entry in m . Keys ) { List < int > al = m [ entry ] ; for ( int i = 0 ; i < al . Count ; i ++ ) arr [ index ++ ] = al [ i ] ; } } static void printArray ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } static public void Main ( ) { int [ ] arr = { 10 , 5 , 3 , 9 , 2 } ; int n = arr . Length ; int x = 7 ; rearrange ( arr , n , x ) ; printArray ( arr , n ) ; } }