Sort integers in array according to their distance from the element K | Java 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
import java . util . * ; class GFG { @ SuppressWarnings ( " unchecked " ) static void distanceSort ( int arr [ ] , int K , int n ) { Vector vd [ ] = new Vector [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { vd [ i ] = new Vector ( ) ; } int pos = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == K ) { pos = i ; break ; } } int i = pos - 1 , j = pos + 1 ; vd [ 0 ] . add ( arr [ pos ] ) ; while ( i >= 0 ) { vd [ pos - i ] . add ( arr [ i ] ) ; -- i ; } while ( j < n ) { vd [ j - pos ] . add ( arr [ j ] ) ; ++ j ; } for ( i = 0 ; i <= Math . max ( pos , n - pos - 1 ) ; ++ i ) { Collections . sort ( vd [ i ] ) ; for ( j = 0 ; j < vd [ i ] . size ( ) ; j ++ ) { int element = ( int ) vd [ i ] . get ( j ) ; System . out . print ( element + " ▁ " ) ; } } } public static void main ( String s [ ] ) { int arr [ ] = { 14 , 1101 , 10 , 35 , 0 } ; int K = 35 ; int n = arr . length ; distanceSort ( arr , K , n ) ; } }