text: Shuffle 2 n integers as a1 | C program for the above approach ; Function to reverse the array from the position ' start ' to position ' end ' ; Stores mid of start and end ; Traverse the array in the range [ start , end ] ; Stores arr [ start + i ] ; Update arr [ start + i ] ; Update arr [ end - i ] ; Utility function to shuffle the given array in the of form { a1 , b1 , a2 , b2 , ... . an , bn } ; Stores the length of the array ; If length of the array is 2 ; Stores mid of the { start , end } ; Divide array into two halves of even length ; Update mid ; Calculate the mid - points of both halves of the array ; Reverse the subarray made from mid1 to mid2 ; Reverse the subarray made from mid1 to mid ; Reverse the subarray made from mid to mid2 ; Recursively calls for both the halves of the array ; Function to shuffle the given array in the form of { a1 , b1 , a2 , b2 , ... . an , bn } ; Function Call ; Print the modified array ; Driver Code ; Given array ; Size of the array ; Shuffles the given array to the required permutation
code: #include <stdio.h> NEW_LINE void reverse ( int arr [ ] , int start , int end ) { int mid = ( end - start + 1 ) / 2 ; for ( int i = 0 ; i < mid ; i ++ ) { int temp = arr [ start + i ] ; arr [ start + i ] = arr [ end - i ] ; arr [ end - i ] = temp ; } return ; } void shuffleArrayUtil ( int arr [ ] , int start , int end ) { int i ; int l = end - start + 1 ; if ( l == 2 ) return ; int mid = start + l / 2 ; if ( l % 4 ) { mid -= 1 ; } int mid1 = start + ( mid - start ) / 2 ; int mid2 = mid + ( end + 1 - mid ) / 2 ; reverse ( arr , mid1 , mid2 - 1 ) ; reverse ( arr , mid1 , mid - 1 ) ; reverse ( arr , mid , mid2 - 1 ) ; shuffleArrayUtil ( arr , start , mid - 1 ) ; shuffleArrayUtil ( arr , mid , end ) ; } void shuffleArray ( int arr [ ] , int N , int start , int end ) { shuffleArrayUtil ( arr , start , end ) ; for ( int i = 0 ; i < N ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 2 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; shuffleArray ( arr , N , 0 , N - 1 ) ; return 0 ; }