Write a program to print all permutations of a given string

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself.
A string of length n has n! permutation.

Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB.


Source Code: 

Download the code  : Permutation of string

#include <iostream>
#include <string.h>
using namespace std;

int count=0;
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)
   {
    count++;
    cout<<count<<": "<<a<<"\n";
   }
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permute(a, l+1, r);
          swap((a+l), (a+i));
       }
   }
}


int main()
{
    char str[100];
    int n;
    cin>>str;
    cout<<"\nPermutations of the given string :\n";
    n = strlen(str);
    permute(str, 0, n-1);
    return 0;
}
 

Comments

Popular posts from this blog

How to create a Chess Game | Game Development in vb.net | Programming