Generate an N | Function to print target array ; Sort the given array ; Seeking for index of elements with minimum diff . ; Seeking for index ; To store target array ; Copying element ; Copying remaining element ; Printing target array ; Given Input ; Function Call
function printArr ( arr , n ) { arr . sort ( ( a , b ) => a - b ) ; let minDifference = Number . MAX_SAFE_INTEGER ; let minIndex = - 1 ; for ( let i = 1 ; i < n ; i ++ ) { if ( minDifference > Math . abs ( arr [ i ] - arr [ i - 1 ] ) ) { minDifference = Math . abs ( arr [ i ] - arr [ i - 1 ] ) ; minIndex = i - 1 ; } } let Arr = new Array ( n ) ; Arr [ 0 ] = arr [ minIndex ] ; Arr [ n - 1 ] = arr [ minIndex + 1 ] ; let pos = 1 ; for ( let i = minIndex + 2 ; i < n ; i ++ ) { Arr [ pos ++ ] = arr [ i ] ; } for ( let i = 0 ; i < minIndex ; i ++ ) { Arr [ pos ++ ] = arr [ i ] ; } for ( let i = 0 ; i < n ; i ++ ) { document . write ( Arr [ i ] + " " ) ; } } let N = 8 ; let arr = [ 4 , 6 , 2 , 6 , 8 , 2 , 6 , 4 ] ; printArr ( arr , N ) ;