C program to display all possible permutations of numbers from 1 to n using Alexander Bogomolyn’s unordered permutation algorithm

This C program implements Alexander Bogomolyn’s unordered permutation algorithm to find all permutations of numbers from 1 to n.

Here is the source code of the C program to display all possible permutations of numbers from 1 to n using Alexander Bogomolyn’s unordered permutation algorithm. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to implement Alexander Bogomolyn's unordered permutation algorithm 
  3.  * to find all permutations of numbers from 1 to n
  4.  */
  5. #include <stdio.h>
  6.  
  7. /*  Function to print all the permutations  */
  8. void print(const int *v, const int size)
  9. {
  10.     int i;
  11.     if (v != 0) {
  12. 	for (i = 0; i < size; i++) {
  13. 	    printf("%4d", v[i] );
  14. 	}
  15. 	printf("\n");
  16.     }
  17. } 
  18. /*  End of print()  */
  19.  
  20. /* Function to generate permutations  */
  21. void visit(int *Value, int N, int k)
  22. {
  23.     static level = -1;
  24.     int i;
  25.     level = level+1; Value[k] = level;
  26.  
  27.     if (level == N)
  28.         print(Value, N);
  29.     else
  30.         for (i = 0; i < N; i++)
  31.             if (Value[i] == 0)
  32.                 visit(Value, N, i);
  33.     level = level-1; Value[k] = 0;
  34. }
  35. /*  End of visit()  */
  36.  
  37. /*  The main() begins  */
  38. int main()
  39. {
  40.     int Value[20], i, N;
  41.     printf("Enter the value of N: ");
  42.     scanf("%d", &N);
  43.     for (i = 0; i < N; i++) {
  44.         Value[i] = 0;
  45.     }
  46.     visit(Value, N, 0);
  47. }

$ gcc permute_alex.c
$ a.out
Enter the value of N: 3
   1   2   3
   1   3   2
   2   1   3
   3   1   2
   2   3   1
   3   2   1

Sanfoundry Global Education & Learning Series – 1000 C Algorithms.

advertisement
advertisement
If you wish to look at all C Algorithms and Solutions, go to C 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.