Print all the permutations of the given string
Print all permutations of a string
Today in this article we will learn how to print all the permutations of a string using C Programming language.
If the length of the string is n then the total number of permutation is n!.
Lets understand this with the help of an example:-
- Input sting:- abc
- Output:- abc,acb,bac,bca,cba,cab.


Algorithm
- Step 1 : Take the string which you need to check if the string is palindrome or not.
- Step 2 : Calculate the length of the string. Let the length of the string be n
- Step 3 : make a function CheckPalindrome() which will take string as parameter
- Step 4:- initialize low and high index and assign low with 0 and high with length-1
- Step 5: Keep comparing characters while they are same
- Step 6:- if the comparison is true for every case then print its palindrome else not palindrome
C++ Code :-
Method 1
// C++ program to print all permutations with duplicates allowed
#include <bits/stdc++.h>
using namespace std;
// Function to swap values at two pointers
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int l, int r)
{
int i;
if (l == r)
cout<<a<<endl;
else
{
for(i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
// Driver program to test permute functions
int main()
{
char str[1000] ;
cout<<"Enter the string :";
gets(str);
cout<<"All the permutations of the string :";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
Output:-
Enter the string :abv
All the permutations of the string :abv
avb
bav
bva
vba
vab
Enter the string :abcf
All the permutations of the string :abcf
abfc
acbf
acfb
afcb
afbc
bacf
bafc
bcaf
bcfa
bfca
bfac
cbaf
cbfa
cabf
cafb
cfab
cfba
fbca
fbac
fcba
fcab
facb
fabc
Login/Signup to comment