Shuffle the position of each Array element by swapping adjacent elements - GeeksforGeeks

21 Apr, 2021
Given an array arr[], the task is to rearrange the array elements by swapping adjacent elements such that no element remains at the same position after swapping. 
Examples:
Input: arr[] = { 1, 2, 3, 4, 5 } Output: 2 1 5 3 4 Explanation: Adjacent elements are swapped as follows: (1, 2 -> 2, 1) (3, 4, 5 -> 5, 3, 4)Input: arr[] = {1, 2, 3, 4} Output: 2 1 4 3 Explanation: Adjacent elements are swapped as follows: 1, 2 -> 2, 1 3, 4 -> 4, 3
Approach: The key observation in the problem is that there can be two cases for the arrays to swap the array elements: 
If the length of the array is even then we can easily Swap 2 Variables without using 3rd variable for every pair of contiguous elements.
If the length of the array is odd then we can do the same as above, but the last 3 elements will not form a pair, So will we can easily Swap those 3 Variables without using 4th variable.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print the arrayvoid print(int a[], int n){    // Loop to iterate over the    // elements of array    for (int i = 0; i < n; i++)        cout << a[i] << " ";} // Function to swap two variables without// using the third variablevoid swapTwo(int& x, int& y){    // Store XOR of all in x    x = x ^ y;     // After this, y has value of x    y = x ^ y;     // After this, x has value of y    x = x ^ y;} // Function to swap three variables// without using fourth variablevoid swapThree(int& a, int& b, int& c){    // Store XOR of all in a    a = a ^ b ^ c;     // After this, b has value of a    b = a ^ b ^ c;     // After this, c has value of b    c = a ^ b ^ c;     // After this, a has value of c    a = a ^ b ^ c;} // Function that swaps n integersvoid rearrangeArray(int a[], int n){    if (n % 2 == 0) {         for (int i = 0; i < n - 1; i += 2) {            // Swap 2 variables without            // using 3rd variable            swapTwo(a[i], a[i + 1]);        }    }    else {        for (int i = 0; i < n - 3; i += 2) {            // Swap 2 variables without            // using 3rd variable            swapTwo(a[i], a[i + 1]);        }         // The last 3 elements will not form        // pair if n is odd        // Hence, swapp 3 variables without        // using 4th variable        swapThree(a[n - 1], a[n - 2], a[n - 3]);    }     // Print the array elements    print(a, n);} // Driver Codeint main(){    // Given array arr[]    int arr[] = { 1, 2, 3, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);     // Function Call    rearrangeArray(arr, n);    return 0;}
// Java program for the above approachimport java.util.*;import java.lang.*; class GFG{     // Function to print the arraystatic void print(int a[], int n){         // Loop to iterate over the    // elements of array    for(int i = 0; i < n; i++)        System.out.print(a[i] + " ");} // Function to swap two variables without// using the third variablestatic void swapTwo(int x, int y, int[] a){         // Store XOR of all in x    a[x] = a[x] ^ a[y];     // After this, y has value of x    a[y] = a[x] ^ a[y];     // After this, x has value of y    a[x] = a[x] ^ a[y];} // Function to swap three variables// without using fourth variablestatic void swapThree(int x, int y,                      int z, int[] a){         // Store XOR of all in a    a[x] = a[x] ^ a[y] ^ a[z];     // After this, b has value of a    a[y] = a[x] ^ a[y] ^ a[z];     // After this, c has value of b    a[z] = a[x] ^ a[y] ^ a[z];     // After this, a has value of c    a[x] = a[x] ^ a[y] ^ a[z];} // Function that swaps n integersstatic void rearrangeArray(int a[], int n){    if (n % 2 == 0)    {        for(int i = 0; i < n - 1; i += 2)        {                         // Swap 2 variables without            // using 3rd variable            swapTwo(i, i + 1, a);        }    }    else    {        for(int i = 0; i < n - 3; i += 2)        {                         // Swap 2 variables without            // using 3rd variable            swapTwo(i, i + 1, a);        }         // The last 3 elements will not form        // pair if n is odd        // Hence, swapp 3 variables without        // using 4th variable        swapThree(n - 1, n - 2, n - 3, a);    }     // Print the array elements    print(a, n);}     // Driver codepublic static void main (String[] args){         // Given array arr[]    int arr[] = { 1, 2, 3, 4, 5 };    int n = arr.length;         // Function call    rearrangeArray(arr, n);    }} // This code is contributed by offbeat
# Python3 program for the above approach # Function to print the arraydef print1(a, n):     # Loop to iterate over the    # elements of array    for i in range(n):        print(a[i], end = " ") # Function to swap two variables without# using the third variabledef swapTwo(x, y):     # Store XOR of all in x    x = x ^ y     # After this, y has value of x    y = x ^ y     # After this, x has value of y    x = x ^ y         return x, y # Function to swap three variables# without using fourth variabledef swapThree(a, b, c):     # Store XOR of all in a    a = a ^ b ^ c     # After this, b has value of a    b = a ^ b ^ c     # After this, c has value of b    c = a ^ b ^ c     # After this, a has value of c    a = a ^ b ^ c     return a , b , c # Function that swaps n integersdef rearrangeArray(a, n):     if (n % 2 == 0):        for i in range (0, n - 1, 2):                         # Swap 2 variables without            # using 3rd variable            a[i], a[i + 1] = swapTwo(a[i], a[i + 1])             else:        for i in range(0, n - 3, 2):                         # Swap 2 variables without            # using 3rd variable            a[i], a[i + 1] = swapTwo(a[i], a[i + 1])         # The last 3 elements will not form        # pair if n is odd        # Hence, swapp 3 variables without        # using 4th variable        a[n - 1], a[n - 2], a[n - 3] = swapThree(a[n - 1],                                                 a[n - 2],                                                 a[n - 3])     # Print the array elements    print1(a, n) # Driver Codeif __name__ == "__main__":     # Given array arr[]    arr = [1, 2, 3, 4, 5 ]    n = len(arr)     # Function call    rearrangeArray(arr, n) # This code is contributed by chitranayal
// C# program for the above approachusing System; class GFG{ // Function to print the arraystatic void print(int []a, int n){         // Loop to iterate over the    // elements of array    for(int i = 0; i < n; i++)        Console.Write(a[i] + " ");} // Function to swap two variables without// using the third variablestatic void swapTwo(ref int x, ref int y){         // Store XOR of all in x    x = x ^ y;     // After this, y has value of x    y = x ^ y;     // After this, x has value of y    x = x ^ y;} // Function to swap three variables// without using fourth variablestatic void swapThree(ref int a, ref int b,                      ref int c){         // Store XOR of all in a    a = a ^ b ^ c;     // After this, b has value of a    b = a ^ b ^ c;     // After this, c has value of b    c = a ^ b ^ c;     // After this, a has value of c    a = a ^ b ^ c;} // Function that swaps n integersstatic void rearrangeArray(int []a, int n){    if (n % 2 == 0)    {        for(int i = 0; i < n - 1; i += 2)        {                         // Swap 2 variables without            // using 3rd variable            swapTwo(ref a[i], ref a[i + 1]);        }    }    else    {        for(int i = 0; i < n - 3; i += 2)        {                         // Swap 2 variables without            // using 3rd variable            swapTwo(ref a[i], ref a[i + 1]);        }         // The last 3 elements will not form        // pair if n is odd        // Hence, swapp 3 variables without        // using 4th variable        swapThree(ref a[n - 1], ref a[n - 2],                  ref a[n - 3]);    }     // Print the array elements    print(a, n);} // Driver Codepublic static void Main(string []s){         // Given array arr[]    int []arr = { 1, 2, 3, 4, 5 };    int n = arr.Length;     // Function call    rearrangeArray(arr, n);}} // This code is contributed by rutvik_56
<script>  // Javascript program for the above approach // Function to print the arrayfunction print( a, n){    // Loop to iterate over the    // elements of array    for (var i = 0; i < n; i++)        document.write( a[i] + " ");} // Function that swaps n integersfunction rearrangeArray( a, n){    if (n % 2 == 0) {         for (var i = 0; i < n - 1; i += 2) {            // Swap 2 variables without            // using 3rd variable            // Store XOR of all in x            a[i] = a[i] ^ a[i + 1];             // After this, y has value of x            a[i + 1] = a[i] ^ a[i + 1];             // After this, x has value of y            a[i] = a[i] ^ a[i + 1];        }    }    else {        for (var i = 0; i < n - 3; i += 2) {            // Swap 2 variables without            // using 3rd variable            // Store XOR of all in x            a[i] = a[i] ^ a[i + 1];             // After this, y has value of x            a[i + 1] = a[i] ^ a[i + 1];             // After this, x has value of y            a[i] = a[i] ^ a[i + 1];        }         // The last 3 elements will not form        // pair if n is odd        // Hence, swapp 3 variables without        // using 4th variable        // Store XOR of all in a        a[n-1] = a[n-1] ^ a[n - 2] ^ a[n - 3];         // After this, b has value of a        a[n - 2] = a[n-1] ^ a[n - 2] ^ a[n - 3];         // After this, c has value of b        a[n - 3] = a[n-1] ^ a[n - 2] ^ a[n - 3];         // After this, a has value of c        a[n-1] = a[n-1] ^ a[n - 2] ^ a[n - 3];    }     // Print the array elements    print(a, n);} // Driver Code// Given array arr[]var arr = [ 1, 2, 3, 4, 5 ];var n = arr.length;// Function CallrearrangeArray(arr, n);  </script>
2 1 4 5 3
 
Time Complexity: O(N) Auxiliary Space: O(1) 
rutvik_56
ukasp
offbeat
itsok
Swap-Program
Arrays
Greedy
Mathematical
School Programming
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Move all negative numbers to beginning and positive to end with constant extra space
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string