Sort integers in array according to their distance from the element K | C ++ implementation to Sort the integers in array according to their distance from given element K present in the array ; Function to get sorted array based on their distance from given integer K ; Vector to store respective elements with their distance from integer K ; Find the position of integer K ; Insert the elements with their distance from K in vector ; Element at distance 0 ; Elements at left side of K ; Elements at right side of K ; Print the vector content in sorted order ; Sort elements at same distance ; Print elements at distance i from K ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void distanceSort ( int arr [ ] , int K , int n ) { vector < int > vd [ n ] ; int pos ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == K ) { pos = i ; break ; } } int i = pos - 1 , j = pos + 1 ; vd [ 0 ] . push_back ( arr [ pos ] ) ; while ( i >= 0 ) { vd [ pos - i ] . push_back ( arr [ i ] ) ; -- i ; } while ( j < n ) { vd [ j - pos ] . push_back ( arr [ j ] ) ; ++ j ; } for ( int i = 0 ; i <= max ( pos , n - pos - 1 ) ; ++ i ) { sort ( begin ( vd [ i ] ) , end ( vd [ i ] ) ) ; for ( auto element : vd [ i ] ) cout << element << " ▁ " ; } } int main ( ) { int arr [ ] = { 14 , 1101 , 10 , 35 , 0 } , K = 35 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; distanceSort ( arr , K , n ) ; return 0 ; }