Alexander Bogomolny’s UnOrdered Permutation Algorithm in C++


Here, we are given a number N. Our task is to find unorder permutation of N using Alexander Bogomolny’s UnOrdered Permutation Algorithm.

Let’s discuss permutation first,

A permutation is the number of ways an item in a set can be uniquely ordered is called a permutation.

Example − Permutation of {4,9,2} would be {4,9,2}, {4,2,9}, {9,4,2}, {9,2,4}, {2,4,9} and {2,9,4}.

Permutations have found usage in defining switching networks in computer networking, parallel processing and also used in a variety of cryptographic algorithms.

Alexander Bogomolny's Unordered Permutation Algorithm

This algorithm computes all possible permutations of first N natural numbers. Given a number N, the permutations are computed from 1 to N.

Let’s take an example to understand the problem,

Input 

N = 3

Output 

1,2,3 ; 1,3,2 ; 2,1,3 ; 2,3,1 ; 3,1,2 ; 3,2,1

Algorithm

1. Build a function with an array, number N, and an integer k as
parameters
2. Initialize the level, as level increases permute the rest of the values
3. When the recursion condition is reached all its values are printed.

Example

Program to show the implementation of our algorithm −

 Live Demo

#include <iostream>
using namespace std;
int level = -1;
void AlexanderBogomolyn(int permutations[], int N, int k) {
   level = level + 1;
   permutations[k] = level;
   if (level == N) {
      for (int i = 0; i < N; i++)
         cout<<permutations[i]<<"\t";
      cout<<endl;
   }
   else{
      for (int i = 0; i < N; i++)
         if (permutations[i] == 0)
            AlexanderBogomolyn(permutations, N, i);
   }
   level = level - 1;
   permutations[k] = 0;
}
int main(){
   int N = 4;
   int permutations[N] = { 0 };
   cout<<"All permutations are :\n";
   AlexanderBogomolyn(permutations, N, 0);
   return 0;
}

Output

All permutations are :
1 2 3 4
1 2 4 3
1 3 2 4
1 4 2 3
1 3 4 2
1 4 3 2
2 1 3 4
2 1 4 3
3 1 2 4
4 1 2 3
3 1 4 2
4 1 3 2
2 3 1 4
2 4 1 3
3 2 1 4
4 2 1 3
3 4 1 2
4 3 1 2
2 3 4 1
2 4 3 1
3 2 4 1
4 2 3 1
3 4 2 1
4 3 2 1

Updated on: 06-Aug-2020

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements