Open In App
Related Articles

Shuffle array {a1, a2, .. an, b1, b2, .. bn} as {a1, b1, a2, b2, a3, b3, ……, an, bn} without using extra space

Improve Article
Improve
Save Article
Save
Like Article
Like

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

We have discussed O(n2) and O(n Log n) solutions of this problem in below post.
Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ……, an, bn} without using extra space
Here a new solution is discussed that works in linear time. We know that the first and last numbers don’t move from their places. And, we keep track of the index from which any number is picked and where the target index is. We know that, if we’re picking ai, it has to go to the index 2 * i – 1 and if bi, it has to go 2 * i. We can check from where we have picked a certain number based on the picking index if it greater or less than n. 
We will have to do this for 2 * n – 2 times, assuming that n = half of length of array. 
We, get two cases, when n is even and odd, hence we initialize appropriately the start variable. 
Note: Indexes are considered 1 based in array for simplicity. 

C++




// C++ program to shuffle an array in O(n) time
// and O(1) extra space
#include <bits/stdc++.h>
using namespace std;
 
// Shuffles an array of size 2n. Indexes
// are considered starting from 1.
void shufleArray(int a[], int n)
{
    n = n / 2;
 
    for (int start = n + 1, j = n + 1, done = 0, i;
         done < 2 * n - 2; done++) {
        if (start == j) {
            start--;
            j--;
        }
 
        i = j > n ? j - n : j;
        j = j > n ? 2 * i : 2 * i - 1;
 
        swap(a[start], a[j]);
    }
}
 
// Driven Program
int main()
{
    // The first element is bogus. We have used
    // one based indexing for simplicity.
    int a[] = {1, 2, 9, 15 };
    int n = sizeof(a) / sizeof(a[0]);
 
    shufleArray(a, n);
 
    for (int i = 1; i < n; i++)
        cout << a[i] << " ";
 
    return 0;
}


Java




// Java program to shuffle an
// array in O(n) time and O(1)
// extra space
import java.io.*;
 
public class GFG {
 
    // Shuffles an array of size 2n.
    // Indexes are considered starting
    // from 1.
    static void shufleArray(int[] a, int n)
    {
        int temp;
        n = n / 2;
 
        for (int start = n + 1, j = n + 1, done = 0, i;
             done < 2 * n - 2; done++) {
            if (start == j) {
                start--;
                j--;
            }
 
            i = j > n ? j - n : j;
            j = j > n ? 2 * i : 2 * i - 1;
            temp = a[start];
            a[start] = a[j];
            a[j] = temp;
        }
    }
 
    // Driver code
    static public void main(String[] args)
    {
        // The first element is bogus. We have used
        // one based indexing for simplicity.
        int[] a = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
        int n = a.length;
 
        shufleArray(a, n);
 
        for (int i = 1; i < n; i++)
            System.out.print(a[i] + " ");
    }
}
 
// This Code is contributed by vt_m.


Python




# Python 3 program to shuffle an array
# in O(n) time and O(1) extra space
 
# Shuffles an array of size 2n. Indexes
# are considered starting from 1.
 
 
def shufleArray(a, n):
 
    n = n // 2
 
    start = n + 1
    j = n + 1
    for done in range(2 * n - 2):
        if (start == j):
            start -= 1
            j -= 1
 
        i = j - n if j > n else j
        j = 2 * i if j > n else 2 * i - 1
 
        a[start], a[j] = a[j], a[start]
 
 
# Driver Code
if __name__ == "__main__":
 
    # The first element is bogus. We have used
    # one based indexing for simplicity.
    a = [-1, 1, 3, 5, 7, 2, 4, 6, 8]
    n = len(a)
 
    shufleArray(a, n)
 
    for i in range(1, n):
        print(a[i], end=" ")
 
# This code is contributed
# by ChitraNayal


C#




// C# program to shuffle an
// array in O(n) time and O(1)
// extra space
using System;
 
public class GFG {
 
    // Shuffles an array of size 2n.
    // Indexes are considered starting
    // from 1.
    static void shufleArray(int[] a, int n)
    {
        int temp;
        n = n / 2;
 
        for (int start = n + 1, j = n + 1, done = 0, i;
             done < 2 * n - 2; done++) {
            if (start == j) {
                start--;
                j--;
            }
 
            i = j > n ? j - n : j;
            j = j > n ? 2 * i : 2 * i - 1;
            temp = a[start];
            a[start] = a[j];
            a[j] = temp;
        }
    }
 
    // Driven code
    static public void Main(String[] args)
    {
        // The first element is bogus. We have used
        // one based indexing for simplicity.
        int[] a = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
        int n = a.Length;
 
        shufleArray(a, n);
 
        for (int i = 1; i < n; i++)
            Console.Write(a[i] + " ");
    }
}
 
// This Code is contributed by vt_m.


Javascript




// Shuffles an array of size 2n.
// Indexes are considered starting
// from 1.
function shuffleArray(a, n) {
  let temp;
  n = Math.floor(n / 2);
 
  for (let start = n + 1, j = n + 1, done = 0, i;
       done < 2 * n - 2;
       done++) {
    if (start == j) {
      start--;
      j--;
    }
 
    i = j > n ? j - n : j;
    j = j > n ? 2 * i : 2 * i - 1;
    temp = a[start];
    a[start] = a[j];
    a[j] = temp;
  }
}
 
// Driven code
// The first element is bogus. We have used
  // one based indexing for simplicity.
const a = [-1, 1, 3, 5, 7, 2, 4, 6, 8];
const n = a.length;
 
shuffleArray(a, n);
 
for (let i = 1; i < n; i++) {
  console.log(a[i] + " ");
}


Output: 

1 2 3 4 5 6 7 8

 

Another Efficient Approach:

The O(n) approach can be improved by sequentially placing the elements at their correct position. 
The criteria of finding the target index remains same. 
The main thing here to realize is that if we swap the current element with an element with greater index, then we can end up traversing on this element which has been placed at its correct position. 
In order to avoid this we increment this element by the max value in the array so when we come to this index we can simply ignore it. 
When we have traversed the array from 2 to n-1, we need to re-produce the original array by subtracting the max value from element which is greater than max value.. 
Note : Indexes are considered 1 based in array for simplicity.
Below is the implementation of the above approach:

C++




#include <iostream>
using namespace std;
 
// Function to shuffle arrays
void Shuffle(int arr[], int n) {
    // Find the maximum element between the last element of the array and the middle element of the array
    int max = (arr[n] > arr[n / 2]) ? arr[n] : arr[n / 2];
 
    // 'i' is traversing index and 'j' index for right half series
    for (int i = 2, j = 0; i <= n - 1; i++) {
        // Check if on left half of array
        if (i <= n / 2) {
            // Check if this index has been visited or not
            if (arr[i] < max) {
                int temp = arr[2 * i - 1];
 
                // Increase the element by max
                arr[2 * i - 1] = arr[i] + max;
 
                // As it's on the left half
                arr[i] = temp;
            }
        }
        // Right half
        else {
            // Index of right half series(b1, b2, b3)
            j++;
 
            // Check if this index has been visited or not
            if (arr[i] < max) {
                int temp = arr[2 * j];
 
                // No need to add max as element is
                arr[2 * j] = arr[i];
 
                // On right half
                arr[i] = temp;
            }
        }
    }
 
    // Re-produce the original array
    for (int i = 2; i <= n - 1; i++) {
        if (arr[i] > max) {
            arr[i] = arr[i] - max;
        }
    }
}
 
// Driver Program
int main() {
    int arr[] = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
    int n = sizeof(arr) / sizeof(arr[0]) - 1;
 
    // Function Call
    Shuffle(arr, n);
 
    for (int i = 1; i <= n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
 
    return 0;
}


C#




// C# program for above approach
using System;
 
class GFG
{
     
    // Function to shuffle arrays
    static void Shuffle(int[] arr, int n)
    {
        int max = (arr[n] > arr[n / 2]) ?
                         arr[n] : arr[n / 2];
 
        // 'i' is traversing index and
        // j index for right half series
        for (int i = 2, j = 0; i <= n - 1; i++)
        {
 
            // Check if on left half of array
            if (i <= n / 2)
            {
                 
                // Check if this index
                // has been visited or not
                if (arr[i] < max)
                {
                    int temp = arr[2 * i - 1];
 
                    // Increase the element by max
                    arr[2 * i - 1] = arr[i] + max;
 
                    // As it i on left half
                    arr[i] = temp;
                }
            }
           
            // Right half
            else
            {
                 
                // Index of right half
                // series(b1, b2, b3)
                j++;
 
                // Check if this index
                // has been visited or not
                if (arr[i] < max)
                {
                    int temp = arr[2 * j];
 
                    // No need to add max
                    // as element is
                    arr[2 * j] = arr[i];
                   
                    // On right half
                    arr[i] = temp;
                }
            }
        }
 
        // Re-produce the original array
        for (int i = 2; i <= n - 1; i++)
        {
            if (arr[i] > max)
            {
                arr[i] = arr[i] - max;
            }
        }
    }
    // Driver Program
    public static void Main()
    {
        int[] arr = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
        int n = arr.Length - 1;
       
        // Function Call
        Shuffle(arr, n);
        for (int i = 1; i <= n; i++)
        {
            Console.Write(arr[i] + " ");
        }
        Console.WriteLine();
    }
}
// This code is contributed by Armaan23


Java




import java.util.*;
 
class Main {
    // Function to shuffle arrays
    static void Shuffle(int[] arr, int n) {
        // Find the maximum element between the last element of the array and the middle element of the array
        int max = (arr[n] > arr[n / 2]) ? arr[n] : arr[n / 2];
 
        // 'i' is traversing index and 'j' index for right half series
        for (int i = 2, j = 0; i <= n - 1; i++) {
            // Check if on left half of array
            if (i <= n / 2) {
                // Check if this index has been visited or not
                if (arr[i] < max) {
                    int temp = arr[2 * i - 1];
 
                    // Increase the element by max
                    arr[2 * i - 1] = arr[i] + max;
 
                    // As it's on the left half
                    arr[i] = temp;
                }
            }
            // Right half
            else {
                // Index of right half series(b1, b2, b3)
                j++;
 
                // Check if this index has been visited or not
                if (arr[i] < max) {
                    int temp = arr[2 * j];
 
                    // No need to add max as element is
                    arr[2 * j] = arr[i];
 
                    // On right half
                    arr[i] = temp;
                }
            }
        }
 
        // Re-produce the original array
        for (int i = 2; i <= n - 1; i++) {
            if (arr[i] > max) {
                arr[i] = arr[i] - max;
            }
        }
    }
 
    // Driver Program
    public static void main(String[] args) {
        int[] arr = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
        int n = arr.length - 1;
 
        // Function Call
        Shuffle(arr, n);
 
        for (int i = 1; i <= n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}


Python3




# Function to shuffle arrays
def Shuffle(arr, n):
    # Find the maximum element between the last element of the array and the middle element of the array
    max = arr[n] if arr[n] > arr[n // 2] else arr[n // 2]
 
    # 'i' is traversing index and 'j' index for right half series
    j = 0
    for i in range(2, n):
        # Check if on left half of array
        if i <= n // 2:
            # Check if this index has been visited or not
            if arr[i] < max:
                temp = arr[2 * i - 1]
 
                # Increase the element by max
                arr[2 * i - 1] = arr[i] + max
 
                # As it's on the left half
                arr[i] = temp
        # Right half
        else:
            # Index of right half series(b1, b2, b3)
            j += 1
 
            # Check if this index has been visited or not
            if arr[i] < max:
                temp = arr[2 * j]
 
                # No need to add max as element is
                arr[2 * j] = arr[i]
 
                # On right half
                arr[i] = temp
 
    # Re-produce the original array
    for i in range(2, n):
        if arr[i] > max:
            arr[i] -= max
 
 
# Driver Program
if __name__ == '__main__':
    arr = [-1, 1, 3, 5, 7, 2, 4, 6, 8]
    n = len(arr) - 1
 
    # Function Call
    Shuffle(arr, n)
 
    for i in range(1, n + 1):
        print(arr[i], end=' ')
    print()


Javascript




function Shuffle(arr, n) {
  // Find the maximum element between the last element of the array and the middle element of the array
  let max = (arr[n] > arr[Math.floor(n / 2)]) ? arr[n] : arr[Math.floor(n / 2)];
 
  // 'i' is traversing index and 'j' index for right half series
  for (let i = 2, j = 0; i <= n - 1; i++) {
    // Check if on left half of array
    if (i <= Math.floor(n / 2)) {
      // Check if this index has been visited or not
      if (arr[i] < max) {
        let temp = arr[2 * i - 1];
 
        // Increase the element by max
        arr[2 * i - 1] = arr[i] + max;
 
        // As it's on the left half
        arr[i] = temp;
      }
    }
    // Right half
    else {
      // Index of right half series(b1, b2, b3)
      j++;
 
      // Check if this index has been visited or not
      if (arr[i] < max) {
        let temp = arr[2 * j];
 
        // No need to add max as element is
        arr[2 * j] = arr[i];
 
        // On right half
        arr[i] = temp;
      }
    }
  }
 
  // Re-produce the original array
  for (let i = 2; i <= n - 1; i++) {
    if (arr[i] > max) {
      arr[i] = arr[i] - max;
    }
  }
}
 
// Driver Program
let arr = [-1, 1, 3, 5, 7, 2, 4, 6, 8];
let n = arr.length - 1;
 
// Function Call
Shuffle(arr, n);
 
for (let i = 1; i <= n; i++) {
  console.log(arr[i] + " ");
}
console.log();


Output

1 2 3 4 5 6 7 8 

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.
 


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials