Sort an array according to absolute difference with a given value " using ▁ constant ▁ extra ▁ space " | PHP program to sort an array based on absolute difference with a given value x . ; Below lines are similar to insertion sort ; Insert arr [ i ] at correct place ; Function to print the array ; Driver Code
< ? php function arrange ( $ arr , $ n , $ x ) { for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ diff = abs ( $ arr [ $ i ] - $ x ) ; $ j = $ i - 1 ; if ( abs ( $ arr [ $ j ] - $ x ) > $ diff ) { $ temp = $ arr [ $ i ] ; while ( abs ( $ arr [ $ j ] - $ x ) > $ diff && $ j >= 0 ) { $ arr [ $ j + 1 ] = $ arr [ $ j ] ; $ j -- ; } $ arr [ $ j + 1 ] = $ temp ; } } return $ arr ; } function print_arr ( $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; } $ arr = array ( 10 , 5 , 3 , 9 , 2 ) ; $ n = sizeof ( $ arr ) ; $ x = 7 ; $ arr1 = arrange ( $ arr , $ n , $ x ) ; print_arr ( $ arr1 , $ n ) ; ? >