Search This Blog

Translate This Page

Wednesday, 27 February 2013

C program to print all permutations of a given string



C program to print all permutations of a given string:



# include <stdio.h>
void swap (char *x, char *y)                //swap values at two pointers
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
void permute(char *a, int i, int n)

{
   int j;
   if (i == n)
     printf("%s\n", a);
   else
   {
        for (j = i; j <= n; j++)
       {
          swap((a+i), (a+j));
          permute(a, i+1, n);
          swap((a+i), (a+j));                 //backtrack
       }
   }
}

int main()
{
   char a[] = "ABC";
   permute(a, 0, 2);
   return 0;
}

No comments:

Post a Comment

Latest Current Visitor

World Clock Time, for View Click on Country