C Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements From 1 to N

This C program computes all possible permutations of numbers from 1 to N using Alexander Bogomolyn’s algorithm. This algorithm is implemented in recursive fashion.

Here is the source code of the C program to find permutations of numbers from 1 to N. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <stdio.h>
  2. void print(const int *v, const int size)
  3. {
  4.     int i;
  5.     if (v != 0) {
  6.     for ( i = 0; i < size; i++) {
  7.         printf("%4d", v[i] );
  8.     }
  9.     printf("\n");
  10.   }
  11. }
  12. void alexanderbogomolyn(int *Value, int N, int k)
  13. {
  14.     static level = -1;
  15.     int i;
  16.     level = level+1; Value[k] = level;
  17.     if (level == N)
  18.         print(Value, N);
  19.     else
  20.         for (i = 0; i < N; i++)
  21.     if (Value[i] == 0)
  22.         alexanderbogomolyn(Value, N, i);
  23.     level = level-1;
  24.     Value[k] = 0;
  25. }
  26. int main()
  27. {
  28.     int N = 4;
  29.     int i;
  30.     int Value[N];
  31.     for (i = 0; i < N; i++) {
  32.       Value[i] = 0;
  33.     }
  34.     printf("\nPermutation using Alexander Bogomolyn's algorithm: ");
  35.     alexanderbogomolyn(Value, N, 0);
  36.     return 0;
  37.  
  38. }

$ gcc permute.c -o permute
$ ./permute
Permutation using Alexander Bogomolyns algorithm:
   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

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.