Skip to content
Related Articles
Sort permutation of N natural numbers using triple cyclic right swaps
• Last Updated : 10 Jun, 2020

Given an array arr[] of size N which contains the permutations of the N natural numbers, the task is to sort the permutations of N natural numbers with the help of triple cyclic right swaps.

Triple Cyclic Right Swaps: refers to the triple cyclic right shift in which –

```arr[i] -> arr[j] -> arr[k] -> arr[i]
```

Examples:

Input: arr[] = {3, 2, 4, 1}
Output: 1
1 3 4
Explanation:
In the operation 1 the index 1, 3 and 4 are choosen and they are cyclic shifted –
arr = arr = 1
arr = arr = 3
arr = arr = 4
Therefore, final array will be {1, 2, 3, 4}.

Input: arr[] = {2, 3, 1}
Output: 1
1 2 3

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to traverse the array and find the elements of the array which is not in its actual sorted position which can be checked by if . Because there are only N natural elements in the array. Finally, find the odd length cyclic rotations required in the array to get the sorted form of the array. If there is any even length cyclic rotations required then it is not possible to sort the elements of the array.

Below is the implementation of the above approach:

## C++

 `// C++ implementation to find the``// number of operations required to``// sort the elements of the array`` ` `#include ``using` `namespace` `std;``#define ll long long`` ` `// Function to sort the permutation``// with the given operations``void` `sortPermutation(ll arr[], ll n)``{``    ``vector > >``        ``ans;``    ``vector p;`` ` `    ``// Vistied array to check the``    ``// array element is at correct``    ``// position or not``    ``bool` `visited = { 0 };`` ` `    ``// Loop to iterate over the elements``    ``// of the given array``    ``for` `(ll i = 1; i <= n; i++) {`` ` `        ``// Condition to check if the``        ``// elements is at its correct``        ``// position``        ``if` `(arr[i] == i) {``            ``visited[i] = 1;``            ``continue``;``        ``}``        ``else` `{`` ` `            ``// Condition to check if the``            ``// element is included in any``            ``// previous cyclic rotations``            ``if` `(!visited[i]) {``                ``ll x = i;``                ``vector v;`` ` `                ``// Loop to find the cyclic``                ``// rotations in required``                ``while` `(!visited[x]) {``                    ``visited[x] = 1;``                    ``v.push_back(x);``                    ``x = arr[x];``                ``}`` ` `                ``// Condition to check if the``                ``// cyclic rotation is a``                ``// valid rotation``                ``if` `((v.size() - 3) % 2 == 0) {``                    ``for` `(ll i = 1; i < v.size();``                         ``i += 2) {`` ` `                        ``ans``                            ``.push_back(``                                ``make_pair(``                                    ``v,``                                    ``make_pair(``                                        ``v[i], v[i + 1])));``                    ``}``                    ``continue``;``                ``}``                ``p.push_back(v);``                ``p.push_back(v[v.size() - 1]);`` ` `                ``// Loop to find the index of the``                ``// cyclic rotation``                ``// for the current index``                ``for` `(ll i = 1; i < v.size() - 1;``                     ``i += 2) {``                    ``ans``                        ``.push_back(``                            ``make_pair(``                                ``v,``                                ``make_pair(``                                    ``v[i], v[i + 1])));``                ``}``            ``}``        ``}``    ``}`` ` `    ``// Condition to if the cyclic``    ``// rotation is a valid rotation``    ``if` `(p.size() % 4) {``        ``cout << -1 << ``"\n"``;``        ``return``;``    ``}`` ` `    ``// Loop to find all the valid operations``    ``// required to sort the permutation``    ``for` `(ll i = 0; i < p.size(); i += 4) {``        ``ans.push_back(``            ``make_pair(p[i],``                      ``make_pair(p[i + 1], p[i + 2])));``        ``ans.push_back(``            ``make_pair(p[i + 2],``                      ``make_pair(p[i], p[i + 3])));``    ``}`` ` `    ``// Total operation required``    ``cout << ans.size() << ``"\n"``;``    ``for` `(ll i = 0; i < ans.size(); i++) {``        ``cout << ans[i].first << ``" "``             ``<< ans[i].second.first << ``" "``             ``<< ans[i].second.second << ``"\n"``;``    ``}``}`` ` `// Driver Code``int` `main()``{``    ``ll arr[] = { 0, 3, 2, 4, 1 };``    ``ll n = 4;`` ` `    ``// Function Call``    ``sortPermutation(arr, n);``    ``return` `0;``}`

## Python3

 `# Python3 implementation to find the``# number of operations required to``# sort the elements of the array`` ` `# Function to sort the permutation``# with the given operations``def` `sortPermutation(arr, n):`` ` `    ``ans ``=` `[]``    ``p ``=` `[]`` ` `    ``# Vistied array to check the``    ``# array element is at correct``    ``# position or not``    ``visited ``=` `[``0``] ``*` `200005`` ` `    ``# Loop to iterate over the elements``    ``# of the given array``    ``for` `i ``in` `range``(``1``, n ``+` `1``):`` ` `        ``# Condition to check if the``        ``# elements is at its correct``        ``# position``        ``if` `(arr[i] ``=``=` `i):``            ``visited[i] ``=` `1``            ``continue`` ` `        ``else``:`` ` `            ``# Condition to check if the``            ``# element is included in any``            ``# previous cyclic rotations``            ``if` `(visited[i]``=``=``False``):``                ``x ``=` `i``                ``v ``=` `[]`` ` `                ``# Loop to find the cyclic``                ``# rotations in required``                ``while` `(visited[x] ``=``=` `False``):``                    ``visited[x] ``=` `1``                    ``v.append(x)``                    ``x ``=` `arr[x]`` ` `                ``# Condition to check if the``                ``# cyclic rotation is a``                ``# valid rotation``                ``if` `((``len``(v) ``-` `3``) ``%` `2` `=``=` `0``):``                    ``for` `i ``in` `range``(``1``, ``len``(v), ``2``):``                        ``ans.append([v[``0``], v[i], v[i ``+` `1``]])``                    ``continue`` ` `                ``p.append(v[``0``])``                ``p.append(v[``len``(v) ``-` `1``])`` ` `                ``# Loop to find the index of the``                ``# cyclic rotation``                ``# for the current index``                ``for` `i ``in` `range``(``1``, ``len``(v) ``-` `1``, ``2``):``                    ``ans.append([v[``0``], v[i], v[i ``+` `1``]])`` ` `    ``# Condition to if the cyclic``    ``# rotation is a valid rotation``    ``if` `(``len``(p) ``%` `4``):``        ``print``(``-``1``)``        ``return`` ` `    ``# Loop to find athe valid operations``    ``# required to sort the permutation``    ``for` `i ``in` `range``(``0``, ``len``(p), ``4``):``        ``ans.append([p[i], p[i ``+` `1``], p[i ``+` `2``]])``        ``ans.append(p[i [``+` `2``], p[i], p[i ``+` `3``]])`` ` `    ``# Total operation required``    ``print``(``len``(ans))``    ``for` `i ``in` `ans:``        ``print``(i[``0``], i[``1``], i[``2``])`` ` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``arr``=``[``0``, ``3``, ``2``, ``4``, ``1``]``    ``n ``=` `4`` ` `    ``# Function Call``    ``sortPermutation(arr, n)`` ` `# This code is contributed by Mohit Kumar`
Output:
```1
1 3 4
```

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up