Given an array arr[], the task is to rearrange the array elements by swapping adjacent elements such that no element remains at 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:

Below is the implementation of the above approach:

  • C++
  • C#

// C++ program for the above approach 

#include <bits/stdc++.h> 

**using** **namespace** std; 

// Function to print the array 

**void** 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 variable 

**void** 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 variable 

**void** 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 integers 

**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(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 Code 

**int** 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; 

Output:

2 1 4 5 3

Time Complexity:_ O(N)_

Auxiliary Space:_ O(1)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #school programming #swap-program

Shuffle the position of each Array element by swapping adjacent elements
8.55 GEEK