Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra space - GeeksforGeeks

11 Aug, 2021
Given an array of 2n elements in the following format { a1, a2, a3, a4, ....., an, b1, b2, b3, b4, ...., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, ......, an, bn } without using extra space. 
Examples: 
Input : arr[] = { 1, 2, 9, 15 }
Output : 1 9 2 15

Input :  arr[] = { 1, 2, 3, 4, 5, 6 }
Output : 1 4 2 5 3 6
Method 1: Brute Force A brute force solution involves two nested loops to rotate the elements in the second half of the array to the left. The first loop runs n times to cover all elements in the second half of the array. The second loop rotates the elements to the left. Note that the start index in the second loop depends on which element we are rotating and the end index depends on how many positions we need to move to the left.
Below is implementation of this approach: 
C++
Java
Python3
C#
Javascript
// C++ Naive program to shuffle an array of size 2n#include <bits/stdc++.h>using namespace std; // function to shuffle an array of size 2nvoid shuffleArray(int a[], int n){    // Rotate the element to the left    for (int i = 0, q = 1, k = n; i < n; i++, k++, q++)        for (int j = k; j > i + q; j--)            swap(a[j - 1], a[j]);} // Driven Programint main(){    int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 };    int n = sizeof(a) / sizeof(a[0]);     shuffleArray(a, n / 2);     for (int i = 0; i < n; i++)        cout << a[i] << " ";     return 0;}
// Java Naive program to shuffle an array of size 2n import java.util.Arrays; public class GFG {    // method to shuffle an array of size 2n    static void shuffleArray(int a[], int n)    {        // Rotate the element to the left        for (int i = 0, q = 1, k = n; i < n; i++, k++, q++)            for (int j = k; j > i + q; j--) {                // swap a[j-1], a[j]                int temp = a[j - 1];                a[j - 1] = a[j];                a[j] = temp;            }    }     // Driver Method    public static void main(String[] args)    {        int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 };         shuffleArray(a, a.length / 2);         System.out.println(Arrays.toString(a));    }}
# Python3 Naive program to# shuffle an array of size 2n # Function to shuffle an array of size 2ndef shuffleArray(a, n):     # Rotate the element to the left    i, q, k = 0, 1, n    while(i < n):            j = k        while(j > i + q):            a[j - 1], a[j] = a[j], a[j - 1]            j -= 1        i += 1        k += 1        q += 1 # Driver Codea = [1, 3, 5, 7, 2, 4, 6, 8]n = len(a)shuffleArray(a, int(n / 2))for i in range(0, n):    print(a[i], end = " ") # This code is contributed by Smitha Dinesh Semwal.
// C# Naive program to shuffle an// array of size 2nusing System; class GFG {    // method to shuffle an array of size 2n    static void shuffleArray(int[] a, int n)    {        // Rotate the element to the left        for (int i = 0, q = 1, k = n;             i < n; i++, k++, q++)            for (int j = k; j > i + q; j--) {                // swap a[j-1], a[j]                int temp = a[j - 1];                a[j - 1] = a[j];                a[j] = temp;            }    }     // Driver Code    public static void Main()    {        int[] a = { 1, 3, 5, 7, 2, 4, 6, 8 };         shuffleArray(a, a.Length / 2);        for (int i = 0; i < a.Length; i++)            Console.Write(a[i] + " ");    }} // This code is contributed// by ChitraNayal
<script>// Javascript Naive program to shuffle an array of size 2n         // method to shuffle an array of size 2n    function shuffleArray(a,n)    {        // Rotate the element to the left        for (let i = 0, q = 1, k = n; i < n; i++, k++, q++)            for (let j = k; j > i + q; j--) {                // swap a[j-1], a[j]                let temp = a[j - 1];                a[j - 1] = a[j];                a[j] = temp;            }    }         // Driver Method    let a=[ 1, 3, 5, 7, 2, 4, 6, 8];    shuffleArray(a, a.length / 2);       document.write(a.join(" "));         //This code is contributed by avanitrachhadiya2155     </script>
Output: 
1 2 3 4 5 6 7 8 
Time Complexity: O(n2)
Method 2: (Divide and Conquer) The idea is to use Divide and Conquer Technique. Divide the given array into half (say arr1[] and arr2[]) and swap second half element of arr1[] with first half element of arr2[]. Recursively do this for arr1 and arr2.
Let us explain with the help of an example. 
Let the array be a1, a2, a3, a4, b1, b2, b3, b4Split the array into two halves: a1, a2, a3, a4 : b1, b2, b3, b4Exchange element around the center: exchange a3, a4 with b1, b2 correspondingly. you get: a1, a2, b1, b2, a3, a4, b3, b4Recursively split a1, a2, b1, b2 into a1, a2 : b1, b2 then split a3, a4, b3, b4 into a3, a4 : b3, b4.Exchange elements around the center for each subarray we get: a1, b1, a2, b2 and a3, b3, a4, b4.
Let the array be a1, a2, a3, a4, b1, b2, b3, b4
Split the array into two halves: a1, a2, a3, a4 : b1, b2, b3, b4
Exchange element around the center: exchange a3, a4 with b1, b2 correspondingly. you get: a1, a2, b1, b2, a3, a4, b3, b4
Recursively split a1, a2, b1, b2 into a1, a2 : b1, b2 then split a3, a4, b3, b4 into a3, a4 : b3, b4.
Exchange elements around the center for each subarray we get: a1, b1, a2, b2 and a3, b3, a4, b4.
Note: This solution only handles the case when n = 2i where i = 0, 1, 2, ...etc.
Below is implementation of this approach: 
C++
Java
Python3
C#
Javascript
// C++ Effective  program to shuffle an array of size 2n #include <bits/stdc++.h>using namespace std; // function to shuffle an array of size 2nvoid shufleArray(int a[], int f, int l){    if (f > l) {        return;    }     // If only 2 element, return    if (l - f == 1)        return;     // finding mid to divide the array    int mid = (f + l) / 2;     // using temp for swapping first half of second array    int temp = mid + 1;     // mmid is use for swapping second half for first array    int mmid = (f + mid) / 2;     // Swapping the element    for (int i = mmid + 1; i <= mid; i++)        swap(a[i], a[temp++]);     // Recursively doing for first half and second half    shufleArray(a, f, mid);    shufleArray(a, mid + 1, l);} // Driven Programint main(){    int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 };    int n = sizeof(a) / sizeof(a[0]);     shufleArray(a, 0, n - 1);     for (int i = 0; i < n; i++)        cout << a[i] << " ";     return 0;}
// Java Effective  program to shuffle an array of size 2n import java.util.Arrays; public class GFG {    // method to shuffle an array of size 2n    static void shufleArray(int a[], int f, int l)    {        if (f > l)            return;         // If only 2 element, return        if (l - f == 1)            return;         // finding mid to divide the array        int mid = (f + l) / 2;         // using temp for swapping first half of second array        int temp = mid + 1;         // mmid is use for swapping second half for first array        int mmid = (f + mid) / 2;         // Swapping the element        for (int i = mmid + 1; i <= mid; i++) {            // swap a[i], a[temp++]            int temp1 = a[i];            a[i] = a[temp];            a[temp++] = temp1;        }         // Recursively doing for first half and second half        shufleArray(a, f, mid);        shufleArray(a, mid + 1, l);    }     // Driver Method    public static void main(String[] args)    {        int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 };         shufleArray(a, 0, a.length - 1);         System.out.println(Arrays.toString(a));    }}
# Python3 effective program to# shuffle an array of size 2n # Function to shuffle an array of size 2ndef shufleArray(a, f, l):     if (f > l):        return     # If only 2 element, return    if (l - f == 1):        return     # Finding mid to divide the array    mid = int((f + l) / 2)     # Using temp for swapping first    # half of the second array    temp = mid + 1     # Mid is use for swapping second    # half for first array    mmid = int((f + mid) / 2)     # Swapping the element    for i in range(mmid + 1, mid + 1):        (a[i], a[temp]) = (a[temp], a[i])        temp += 1     # Recursively doing for first    # half and second half    shufleArray(a, f, mid)    shufleArray(a, mid + 1, l)  # Driver Codea = [1, 3, 5, 7, 2, 4, 6, 8]n = len(a)shufleArray(a, 0, n - 1) for i in range(0, n):    print(a[i], end = " ") # This code is contributed by Smitha Dinesh Semwal
// C# program program to merge two// sorted arrays with O(1) extra space.using System; // method to shuffle an array of size 2n public class GFG {    // method to shuffle an array of size 2n    static void shufleArray(int[] a, int f, int l)    {        if (f > l)            return;         // If only 2 element, return        if (l - f == 1)            return;         // finding mid to divide the array        int mid = (f + l) / 2;         // using temp for swapping first half of second array        int temp = mid + 1;         // mmid is use for swapping second half for first array        int mmid = (f + mid) / 2;         // Swapping the element        for (int i = mmid + 1; i <= mid; i++) {            // swap a[i], a[temp++]            int temp1 = a[i];            a[i] = a[temp];            a[temp++] = temp1;        }         // Recursively doing for first half and second half        shufleArray(a, f, mid);        shufleArray(a, mid + 1, l);    }     // Driver Method    public static void Main()    {        int[] a = { 1, 3, 5, 7, 2, 4, 6, 8 };         shufleArray(a, 0, a.Length - 1);        for (int i = 0; i < a.Length; i++)            Console.Write(a[i] + " ");    }} /*This code is contributed by 29AjayKumar*/
<script> // Javascript Effective program to// shuffle an array of size 2n     // method to shuffle an array of size 2nfunction shufleArray(a, f, l){    if (f > l)        return;     // If only 2 element, return    if (l - f == 1)        return;     // Finding mid to divide the array    let mid = Math.floor((f + l) / 2);     // Using temp for swapping first    // half of second array    let temp = mid + 1;     // mmid is use for swapping second    // half for first array    let mmid = Math.floor((f + mid) / 2);     // Swapping the element    for(let i = mmid + 1; i <= mid; i++)    {                 // Swap a[i], a[temp++]        let temp1 = a[i];        a[i] = a[temp];        a[temp++] = temp1;    }     // Recursively doing for first    // half and second half    shufleArray(a, f, mid);    shufleArray(a, mid + 1, l);} // Driver Codelet a = [ 1, 3, 5, 7, 2, 4, 6, 8 ];shufleArray(a, 0, a.length - 1); document.write(a.join(" ")); // This code is contributed by rag2127     </script>
Output: 
1 2 3 4 5 6 7 8 
Time Complexity: O(n log n)Linear time solution
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
ukasp
29AjayKumar
ADITYA_VERMA_
coder_krishna
avanitrachhadiya2155
rag2127
akshaysingh98088
Adobe
Arrays
Divide and Conquer
Recursion
Adobe
Arrays
Recursion
Divide and Conquer
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Program for Tower of Hanoi