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

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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, 1, 3, 5, 7, 2, 4, 6, 8 };
    int n = sizeof(a) / sizeof(a[0]);
  
    shufleArray(a, n);
  
    for (int i = 1; i < n; i++)
        cout << a[i] << " ";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


Python 3

# 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#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP 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.
function shufleArray($a, $n)
{
      
    $k = intval($n / 2);
  
    for ($start = $k + 1, 
         $j = $k + 1, $done = 0; 
         $done < 2 * $k - 2; $done++)
    {
        if ($start == $j)
        {
            $start--;
            $j--;
        }
  
        $i = $j > $k ? $j - $k : $j;
        $j = $j > $k ? 2 * $i : 2 * $i - 1;
        $temp = $a[$start];
        $a[$start] = $a[$j];
        $a[$j] = $temp;
  
    }
    for ($i = 1; $i < $n; $i++)
                echo $a[$i] . " ";
}
  
// Driver code
  
// The first element is bogus. 
// We have used one based 
// indexing for simplicity.
$a = array(-1, 1, 3, 5, 7, 2, 4, 6, 8);
$n = count($a);
shufleArray($a, $n);
      
// This code is contributed by Sam007
?>

chevron_right


Output :

1 2 3 4 5 6 7 8

This article is contributed by azam58. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.



My Personal Notes arrow_drop_up

Improved By : vt_m, Sam007, Ita_c



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.