C++ Program to Generate All Permutations using BackTracking

«
»
This C++ Program demonstrates the generation of all Permutations using BackTracking.

Here is source code of the C++ Program to Generate All Permutations using BackTracking. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Generate All Permutations using BackTracking
  3.  */
  4. #include <iostream>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <cstdlib>
  8. using namespace std;
  9.  
  10. /* swap values at two pointers */
  11. void swap (char *x, char *y)
  12. {
  13.     char temp;
  14.     temp = *x;
  15.     *x = *y;
  16.     *y = temp;
  17. }
  18.  
  19. /* print permutations of string */
  20. void permute(char *a, int i, int n)
  21. {
  22.     int j;
  23.     if (i == n)
  24.         cout<<a<<endl;
  25.     else
  26.     {
  27.         for (j = i; j <= n; j++)
  28.         {
  29.             swap((a + i), (a + j));
  30.             permute(a, i + 1, n);
  31.             swap((a+i), (a + j));
  32.        }
  33.    }
  34. }
  35.  
  36. /* Main*/
  37. int main()
  38. {
  39.     char a[] = "abcd";
  40.     permute(a, 0, 3);
  41.     return 0;
  42. }

advertisement
$ g++ permutations_back.cpp
$ a.out
 
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc
 
------------------
(program exited with code: 1)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

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!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn