Find all permutations of String using Recursion


# include <stdio.h>
# include <string.h>

/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
 
/* Function to print permutations of string */
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";
   int l=strlen(a);
   printf("String length => %d",l);
   permute(a, 0, l-1);
   getchar();
   return 0;
}

Output:-

String length => 3
ABC
ACB
BAC
BCA
CBA
CAB

0 comments :