VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shuffle-the-position-of-each-array-element-by-swapping-adjacent-elements/

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


  • Courses
  • Tutorials
  • Interview Prep

Shuffle the position of each Array element by swapping adjacent elements

Last Updated : 15 Jul, 2025

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:
 


Below is the implementation of the above approach:
 


Output: 
2 1 4 5 3

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 

Comment
Article Tags:
Article Tags: