Generate an N | Java program for above approach ; 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 ; Driver code ; Given Input ; Function Call
import java . io . * ; import java . util . * ; class GFG { public static void printArr ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int minDifference = 1000000007 ; int minIndex = - 1 ; for ( int 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 ; } } int Arr [ ] = new int [ n ] ; Arr [ 0 ] = arr [ minIndex ] ; Arr [ n - 1 ] = arr [ minIndex + 1 ] ; int pos = 1 ; for ( int i = minIndex + 2 ; i < n ; i ++ ) { Arr [ pos ++ ] = arr [ i ] ; } for ( int i = 0 ; i < minIndex ; i ++ ) { Arr [ pos ++ ] = arr [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( Arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 8 ; int arr [ ] = { 4 , 6 , 2 , 6 , 8 , 2 , 6 , 4 } ; printArr ( arr , N ) ; } }