Generate an N | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int minDifference = INT_MAX ; int minIndex = -1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( minDifference > abs ( arr [ i ] - arr [ i - 1 ] ) ) { minDifference = abs ( arr [ i ] - arr [ i - 1 ] ) ; minIndex = i - 1 ; } } int Arr [ 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 ++ ) { cout << Arr [ i ] << " ▁ " ; } } int main ( ) { int N = 8 ; int arr [ ] = { 4 , 6 , 2 , 6 , 8 , 2 , 6 , 4 } ; printArr ( arr , N ) ; return 0 ; }