Sort an array according to absolute difference with a given value " using ▁ constant ▁ extra ▁ space " | C ++ 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 ; Main Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void arrange ( int arr [ ] , int n , int x ) { for ( int i = 1 ; i < n ; i ++ ) { int diff = abs ( arr [ i ] - x ) ; int j = i - 1 ; if ( abs ( arr [ j ] - x ) > diff ) { int temp = arr [ i ] ; while ( abs ( arr [ j ] - x ) > diff && j >= 0 ) { arr [ j + 1 ] = arr [ j ] ; j -- ; } arr [ j + 1 ] = temp ; } } } void print ( 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 ; arrange ( arr , n , x ) ; print ( arr , n ) ; return 0 ; }